diff --git a/CHANGELOG.md b/CHANGELOG.md index 892ef8d9..ddd8eef6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -126,6 +126,32 @@ 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 classification gate. A + primitive list element allowed a `1e-10` tolerance, but a field, a nested + model, a `List[StructuredModel]` pair, `EvalResult.matched` and + `binary_compare()` 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. Each of these 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, and `ComparisonInfo.compare()` and + `ComparableFieldConfig.compare()` return it; + - opens a list pair for field-by-field evaluation; + - sets `EvalResult.matched`, makes `BaseComparator.binary_compare()` return + `(1, 0)`, 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. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box + `iou_thresholds` are separate metrics and keep their exact comparison + ([#417](https://github.com/awslabs/stickler/issues/417)). See + [Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold) + - **Breaking:** `evaluator_format=True` output carries `non_matches` only with `document_non_matches=True`, as the default `compare_with()` dict does, so `result["non_matches"]` without it now raises `KeyError`. It always wrote diff --git a/docs/docs/API-Reference/auto.md b/docs/docs/API-Reference/auto.md index 5645647d..ec8f5530 100644 --- a/docs/docs/API-Reference/auto.md +++ b/docs/docs/API-Reference/auto.md @@ -49,7 +49,7 @@ above: | `recall` | `float` | `cm_recall` | | `f1` | `float` | `cm_f1` | | `accuracy` | `float` | `cm_accuracy` | -| `matched` | `bool` | `overall_score >= match_threshold`. A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. | +| `matched` | `bool` | `overall_score >= match_threshold` (see [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. | | `confusion_matrix` | `dict` | The full confusion-matrix subtree | | `raw` | `dict` | The unmodified `compare_with()` result | diff --git a/docs/docs/Advanced/classification-logic.md b/docs/docs/Advanced/classification-logic.md index d26993e4..81df4a69 100644 --- a/docs/docs/Advanced/classification-logic.md +++ b/docs/docs/Advanced/classification-logic.md @@ -39,7 +39,7 @@ False Alarm (FA) and False Discovery (FD) together make up the broader False Pos Lists use the [Hungarian algorithm](hungarian-matching.md) for optimal element pairing. 1. **Empty lists**: `[] vs []` is TN; `[] vs [items]` produces one FA per item; `[items] vs []` produces one FN per item. -2. **Matched elements**: similarity >= threshold is TP; below threshold is FD. +2. **Matched elements**: similarity >= threshold is TP; below threshold is FD. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). 3. **Unmatched elements**: leftover GT elements are FN; leftover EST elements are FA. 4. **`None` elements**: absent, so they are not matched or counted. A list of only `None` is an empty list. See [`None` elements in a list](#none-elements-in-a-list). @@ -97,7 +97,7 @@ Result: TP=0, FA=0, FN=0, FD=3 ### Nested Objects -Nested objects are evaluated recursively, field by field. +Nested objects are evaluated recursively, field by field, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). | Condition | Classification | |-----------|---------------| @@ -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 less than `1e-10` under it, at every gate listed in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold), 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. diff --git a/docs/docs/Advanced/hungarian-matching.md b/docs/docs/Advanced/hungarian-matching.md index 0ee42eb7..61116ef0 100644 --- a/docs/docs/Advanced/hungarian-matching.md +++ b/docs/docs/Advanced/hungarian-matching.md @@ -26,7 +26,7 @@ The Hungarian algorithm solves the assignment problem in O(n^3) time, producing ### 3. Threshold-Gated Classification -Each matched pair is classified using `StructuredModel.match_threshold`: +Each matched pair is classified using `StructuredModel.match_threshold`, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold): | Condition | Classification | Nested analysis? | |-----------|---------------|-----------------| @@ -195,7 +195,7 @@ The threshold for Hungarian classification comes from the element model's `match ### Recursion Gating ``` -IF object_similarity >= match_threshold: +IF object_similarity meets match_threshold: classification = TP recurse into nested field analysis ELSE: diff --git a/docs/docs/Advanced/threshold-gated-evaluation.md b/docs/docs/Advanced/threshold-gated-evaluation.md index 7c2e4675..a55f4c71 100644 --- a/docs/docs/Advanced/threshold-gated-evaluation.md +++ b/docs/docs/Advanced/threshold-gated-evaluation.md @@ -90,15 +90,30 @@ class Order(StructuredModel): Given three GT products and three Pred products: -### Good Match (similarity >= 0.8) +```python +gt = Order(order_id="ORD-1", products=[ + Product(product_id="PROD-001", name="Laptop", price=999.99), + Product(product_id="PROD-002", name="Mouse", price=29.99), + Product(product_id="PROD-003", name="Cable", price=14.99), +]) +pred = Order(order_id="ORD-1", products=[ + Product(product_id="PROD-001", name="Laptop Computer", price=999.99), + Product(product_id="PROD-002", name="Different Product", price=99.99), + Product(product_id="PROD-004", name="New Product", price=19.99), +]) +result = gt.compare_with(pred, include_confusion_matrix=True, document_non_matches=True) +``` + +### Good Match (meets 0.8) **GT:** `Product("PROD-001", "Laptop", 999.99)` **Pred:** `Product("PROD-001", "Laptop Computer", 999.99)` +- Similarity: `(3 * 1.0 + 2 * 0.4 + 1 * 1.0) / 6`, which floating point evaluates to `0.7999999999999999`. It meets `0.8` through the [rounding tolerance](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). - Classification: **TP** - Nested field analysis is performed: - `product_id`: TP (exact match) - - `name`: TP (similarity ~0.9) + - `name`: FD (Levenshtein similarity 0.4, under its 0.7 threshold) - `price`: TP (exact match) ### Poor Match (similarity < 0.8) @@ -106,48 +121,54 @@ Given three GT products and three Pred products: **GT:** `Product("PROD-002", "Mouse", 29.99)` **Pred:** `Product("PROD-002", "Different Product", 99.99)` +- Similarity: `(3 * 1.0 + 2 * 0.118 + 1 * 0.8) / 6`, about `0.6725` - Classification: **FD** - No nested field analysis -- the objects are too dissimilar for field-level breakdown to be useful. -### Unmatched Items +### Weak Pairing -**GT:** `Product("PROD-003", "Cable", 14.99)` -- **FN** (no counterpart in Pred) -**Pred:** `Product("PROD-004", "New Product", 19.99)` -- **FA** (no counterpart in GT) +**GT:** `Product("PROD-003", "Cable", 14.99)` +**Pred:** `Product("PROD-004", "New Product", 19.99)` -No nested analysis for either. +- Similarity: `0.1333` +- Classification: **FD**, with no nested analysis + +Hungarian matching pairs every item when both lists have the same length, so +these two are paired even though they share almost nothing. An item is left +unmatched only when one list is longer: without `New Product` in Pred, `Cable` +would be an **FN**, and without `Cable` in GT, `New Product` would be an **FA**. +Neither is broken down into fields. ## Result Structure +The `products` counts and the `non_matches` from the run above, with other keys +left out and scores rounded to four places: + ```json { - "products": { + "confusion_matrix": { "fields": { "products": { "overall": { - "tp": 1, "fd": 1, "fn": 1, "fa": 1, - "derived": { "cm_precision": 0.5, "cm_recall": 0.5, "cm_f1": 0.5 } + "tp": 1, "fd": 2, "fn": 0, "fa": 0, + "derived": { "cm_precision": 0.3333, "cm_recall": 1.0, "cm_f1": 0.5 } }, "fields": { - "product_id": { "tp": 1 }, - "name": { "tp": 1 }, - "price": { "tp": 1 } - }, - "non_matches": [ - { - "type": "FD", - "gt_object": "Product(PROD-002, Mouse, 29.99)", - "pred_object": "Product(PROD-002, Different Product, 99.99)", - "similarity": 0.3 - }, - { "type": "FN", "gt_object": "Product(PROD-003, Cable, 14.99)" }, - { "type": "FA", "pred_object": "Product(PROD-004, New Product, 19.99)" } - ] - } + "product_id": { "overall": { "tp": 1 } }, + "name": { "overall": { "fd": 1 } }, + "price": { "overall": { "tp": 1 } } + } + } } }, + "non_matches": [ + { "field_path": "products[0].name", "non_match_type": "false_discovery", "similarity_score": 0.4 }, + { "field_path": "products[1]", "non_match_type": "false_discovery", "similarity_score": 0.6725 }, + { "field_path": "products[2]", "non_match_type": "false_discovery", "similarity_score": 0.1333 } + ] } ``` -Field-level metrics appear only for the single TP pair. The `non_matches` list -documents each FD, FN, and FA once at object level; `field_comparisons` uses the -same boundary. Neither report expands a rejected or unmatched object into -leaves. +Field-level metrics appear only for the single TP pair, and its `name` is the +only leaf in `non_matches`. That list documents each rejected pair once at +object level, as it would an FN or FA; `field_comparisons` uses the same +boundary. Neither report expands a rejected or unmatched object into leaves. ## Delegation Pattern @@ -203,7 +224,8 @@ field's own `threshold` decides that verdict. See `overall_score` is the scalar summary, and `EvalResult.matched` from `stickler.evaluate()` is the object-level verdict -(`overall_score >= match_threshold`). +(`overall_score >= match_threshold`, see +[Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). For the raw object similarity used by Hungarian matching, fields absent on both sides are omitted from both totals. They remain TNs in the confusion matrix, but do not help a pair clear `match_threshold`. If no fields remain, the similarity is defined as `1.0`, because nothing disagreed. @@ -211,7 +233,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 less than `1e-10` under it, so a rounding error does not flip the verdict. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). **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. diff --git a/docs/docs/Getting-Started/Contributing/architecture.md b/docs/docs/Getting-Started/Contributing/architecture.md index ea981f6f..3b59855d 100644 --- a/docs/docs/Getting-Started/Contributing/architecture.md +++ b/docs/docs/Getting-Started/Contributing/architecture.md @@ -211,14 +211,14 @@ The source header documents preserved behavioral bugs: #### Threshold-Gated Recursion Internals -Field-level detail is only generated for object pairs with `similarity >= match_threshold`. Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization. +Field-level detail is only generated for object pairs with `similarity >= match_threshold` (see [Meeting a Threshold](../thresholds-and-metrics.md#meeting-a-threshold)). Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization. ```python -# See: structured_list_comparator.py:243-249 +# See: structured_list_comparator.py:245-249 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) ] ``` diff --git a/docs/docs/Getting-Started/thresholds-and-metrics.md b/docs/docs/Getting-Started/thresholds-and-metrics.md index 985ff168..7e144e39 100644 --- a/docs/docs/Getting-Started/thresholds-and-metrics.md +++ b/docs/docs/Getting-Started/thresholds-and-metrics.md @@ -38,7 +38,7 @@ class Invoice(StructuredModel): **What it gates:** -- **TP vs FD classification:** If `similarity >= threshold`, the field is a True Positive. Otherwise, it's a False Discovery. +- **TP vs FD classification:** If `similarity >= threshold` (see [Meeting a Threshold](#meeting-a-threshold)), the field is a True Positive. Otherwise, it's a False Discovery. - **Score clipping:** When `clip_under_threshold=True` (the default), scores below the threshold are zeroed out in the weighted average. **Default:** `0.5` @@ -129,6 +129,10 @@ Field threshold → threshold named on the comparator → `0.5`. A comparator's *default* threshold is not part of that chain. `LevenshteinComparator()` does not contribute its 0.7, because those defaults were chosen for `binary_compare()` and were never audited as classification cutoffs. `DateComparator` is the clearest case: it defaults to `1.0` while awarding `0.7` partial credit for a match with no year, so adopting its default would clip its own feature to zero. +## Meeting a Threshold + +A score meets its threshold when it is at or above it, or less than `1e-10` under it. The allowance absorbs floating-point rounding: `0.7 + 0.1` is `0.7999999999999999`, which meets `0.8`, while `0.8 - 1e-9` does not. Field, list element and list pair classification, score clipping, recursion into a list pair, `EvalResult.matched` and `binary_compare()` all use this one test, `ThresholdHelper.is_above_threshold`, so wherever these docs write `similarity >= threshold` they mean it. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box `iou_thresholds` are separate metrics and keep their exact comparison. + --- ## Metrics Glossary diff --git a/docs/docs/Guides/Evaluation/README.md b/docs/docs/Guides/Evaluation/README.md index ed67aad2..ab4e66cd 100644 --- a/docs/docs/Guides/Evaluation/README.md +++ b/docs/docs/Guides/Evaluation/README.md @@ -64,7 +64,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit See the [Comparators](../Comparators/README.md) section for the complete list and detailed descriptions. -**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields. +**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. See [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields. **`weight`** -- Controls how much a field contributes to the overall score. The overall score is computed as: diff --git a/docs/docs/Guides/Evaluation/understanding-results.md b/docs/docs/Guides/Evaluation/understanding-results.md index 26a631ca..8e7334a3 100644 --- a/docs/docs/Guides/Evaluation/understanding-results.md +++ b/docs/docs/Guides/Evaluation/understanding-results.md @@ -46,7 +46,7 @@ Maps each field name to its similarity score (0.0 to 1.0). For nested objects, t ### Asking whether anything failed -`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold`. +`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold` (see [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). To ask whether anything at all went wrong, read **both** rollup nodes, because they scope different things: diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index 03c44fbf..dfeef16b 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -63,17 +63,20 @@ 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` +## 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`. +**`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 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. +**The threshold test is `ThresholdHelper.is_above_threshold`**, the one every +classification gate listed in +[Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold) +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 @@ -86,9 +89,9 @@ themselves: | `ComparisonHelper.compare_unordered_lists` | hands them to `unordered_list_metrics`, which counts against its own `classification_threshold` | | `ComparisonHelperBase.get_optimal_assignments` | provides pairings for direct report-helper calls; `compare_with` reports instead reuse the scoring pass's pairings | -`unordered_list_metrics` uses the same derivation as `calculate_metrics`, so the -two agree on what a count means. The remaining difference is the tolerant -threshold test noted above. +`unordered_list_metrics` uses the same derivation and the same threshold test as +`calculate_metrics`, so for the same pairs and threshold the two return the same +counts. Because these callers do not read the counts, a change to how `calculate_metrics` classifies cannot move an evaluator score. It is a public API in its own right diff --git a/src/stickler/algorithms/hungarian.py b/src/stickler/algorithms/hungarian.py index 1f68d98d..fa4f3d97 100644 --- a/src/stickler/algorithms/hungarian.py +++ b/src/stickler/algorithms/hungarian.py @@ -289,15 +289,21 @@ 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 classification gate listed in Meeting a Threshold 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) @@ -322,7 +328,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 diff --git a/src/stickler/auto/facade.py b/src/stickler/auto/facade.py index 93257aab..46fc16f1 100644 --- a/src/stickler/auto/facade.py +++ b/src/stickler/auto/facade.py @@ -26,6 +26,7 @@ StructuredModel, _annotation_is_list, ) +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 @@ -79,8 +80,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]]: @@ -138,7 +144,7 @@ def explain(self) -> Dict[str, Dict[str, Any]]: score == 0.0 and raw_sim and threshold is not None - and raw_sim < threshold + and ThresholdHelper.is_below_threshold(raw_sim, threshold) and not self._is_list_of_models(name) ): if self._is_list_field(name): diff --git a/src/stickler/comparators/base.py b/src/stickler/comparators/base.py index 69cfd481..9d319575 100644 --- a/src/stickler/comparators/base.py +++ b/src/stickler/comparators/base.py @@ -238,9 +238,11 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]: """Compare two values and return a binary result as (tp, fp) tuple. This method converts the continuous similarity score to a binary decision - based on the threshold. If the similarity is greater than or equal to the - threshold, it returns (1, 0) indicating true positive. Otherwise, it returns - (0, 1) indicating false positive. + based on the threshold. If the similarity meets the threshold, it returns + (1, 0) indicating true positive. Otherwise, it returns (0, 1) indicating + false positive. The test is ``ThresholdHelper.is_above_threshold``, the + one every classification gate listed in Meeting a Threshold uses, so a + score less than ``1e-10`` under the threshold meets it. Args: str1: First value @@ -250,8 +252,15 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]: Tuple of (tp, fp) where tp is 1 if similar, 0 otherwise, and fp is the opposite """ + # Imported here, as in HungarianMatcher.calculate_metrics, so this + # module has no import-time dependency on the evaluator package, which + # imports it. + from stickler.structured_object_evaluator.models.threshold_helper import ( + ThresholdHelper, + ) + score = self.compare(str1, str2) - if score >= self.threshold: + if ThresholdHelper.is_above_threshold(score, self.threshold): return (1, 0) # True positive else: return (0, 1) # False positive diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index 6821f24b..18615aa9 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -11,6 +11,7 @@ from .hungarian_helper import HungarianHelper from .null_helper import NullHelper from .reporting_context import ReportingContext +from .threshold_helper import ThresholdHelper DEFAULT_MATCH_THRESHOLD = 0.7 @@ -162,7 +163,11 @@ def process_matched_pairs( is_match = ( bool(verdicts[pair_index]) if verdicts is not None - else bool(similarity_score >= match_threshold) + else bool( + ThresholdHelper.is_above_threshold( + similarity_score, match_threshold + ) + ) ) # Create reason diff --git a/src/stickler/structured_object_evaluator/models/comparison_info.py b/src/stickler/structured_object_evaluator/models/comparison_info.py index 16935582..bd5f653d 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_info.py +++ b/src/stickler/structured_object_evaluator/models/comparison_info.py @@ -7,6 +7,8 @@ from stickler.comparators.base import BaseComparator from stickler.comparators.levenshtein import LevenshteinComparator +from .threshold_helper import ThresholdHelper + class ComparisonInfo: """Container for comparison configuration. @@ -56,7 +58,11 @@ def compare(self, value1: Any, value2: Any) -> float: similarity = self.comparator.compare(value1, value2) # Apply threshold (if below threshold, return 0) - return 0.0 if similarity < self.threshold else similarity + return ( + 0.0 + if ThresholdHelper.is_below_threshold(similarity, self.threshold) + else similarity + ) def __repr__(self) -> str: """Return string representation.""" @@ -130,7 +136,9 @@ def compare(self, value1: Any, value2: Any) -> float: similarity = self.comparator.compare(value1, value2) # Apply threshold if clip_under_threshold is enabled - if self.clip_under_threshold and similarity < self.threshold: + if self.clip_under_threshold and ThresholdHelper.is_below_threshold( + similarity, self.threshold + ): return 0.0 return similarity diff --git a/src/stickler/structured_object_evaluator/models/confidence/README.md b/src/stickler/structured_object_evaluator/models/confidence/README.md index 08c3f1b0..f44811d0 100644 --- a/src/stickler/structured_object_evaluator/models/confidence/README.md +++ b/src/stickler/structured_object_evaluator/models/confidence/README.md @@ -25,7 +25,7 @@ class ConfidencePair(BaseModel): similarity: float # Raw comparator similarity score (0.0–1.0) ``` -`is_match` is threshold-gated: `raw_score >= ComparableField.threshold`. This means a field with similarity 0.65 and threshold 0.7 is `is_match=False`, even though it's partially correct. The `similarity` field preserves the continuous score for future metrics that want to correlate confidence with degree of correctness rather than binary match. +`is_match` is threshold-gated: `raw_score >= ComparableField.threshold`, with the rounding tolerance described in [Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold). This means a field with similarity 0.65 and threshold 0.7 is `is_match=False`, even though it's partially correct. The `similarity` field preserves the continuous score for future metrics that want to correlate confidence with degree of correctness rather than binary match. ## Adding a New Metric diff --git a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py index 0c885de0..e60b447e 100644 --- a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py +++ b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py @@ -8,6 +8,7 @@ from .field_helper import FieldHelper from .null_helper import NullHelper +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -89,7 +90,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 diff --git a/src/stickler/structured_object_evaluator/models/field_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 8824a825..89276fff 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparator.py +++ b/src/stickler/structured_object_evaluator/models/field_comparator.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional from .reporting_context import ReportingContext +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -70,7 +71,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: @@ -136,7 +137,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 diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index 22f82e4f..0e28a0c3 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -10,6 +10,7 @@ from .field_comparison_helper import FieldComparisonHelper from .null_helper import NullHelper from .reporting_context import ReportingContext +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -146,7 +147,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: diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py index adb935b8..6667b3e2 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py @@ -5,6 +5,7 @@ from .comparison_helper_base import ComparisonHelperBase from .null_helper import NullHelper from .reporting_context import ReportingContext +from .threshold_helper import ThresholdHelper class FieldComparisonHelper(ComparisonHelperBase): @@ -148,7 +149,10 @@ 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 + score_is_match = ThresholdHelper.is_above_threshold( + field_score, info.threshold + ) + field_is_match = score_is_match field_result = field_results.get(nested_field_name) if field_result is not None: metrics = field_result.get("overall", field_result) @@ -163,7 +167,7 @@ def _extract_entries_from_objects( if ( field_result is not None and "fields" in field_result - and field_is_match != (field_score >= info.threshold) + and field_is_match != score_is_match ): if field_is_match: score_text = f"{field_score:.3f}" diff --git a/src/stickler/structured_object_evaluator/models/metrics_helper.py b/src/stickler/structured_object_evaluator/models/metrics_helper.py index c90c631d..b7c21d42 100644 --- a/src/stickler/structured_object_evaluator/models/metrics_helper.py +++ b/src/stickler/structured_object_evaluator/models/metrics_helper.py @@ -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.""" @@ -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 diff --git a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py index f10e0ee4..b7bf7b66 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -15,6 +15,7 @@ from .metrics_helper import MetricsHelper from .null_helper import NullHelper from .reporting_context import ReportingContext +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -155,7 +156,10 @@ def _calculate_object_level_metrics( # Count OBJECTS, not individual fields tp_objects = 0 # Objects with similarity >= match_threshold fd_objects = 0 # Objects with similarity < match_threshold - verdicts = [score >= match_threshold for _, _, score in matched_pairs] + verdicts = [ + ThresholdHelper.is_above_threshold(score, match_threshold) + for _, _, score in matched_pairs + ] for is_match in verdicts: if is_match: tp_objects += 1 diff --git a/tests/structured_object_evaluator/test_threshold_tolerance.py b/tests/structured_object_evaluator/test_threshold_tolerance.py new file mode 100644 index 00000000..7dee3ccb --- /dev/null +++ b/tests/structured_object_evaluator/test_threshold_tolerance.py @@ -0,0 +1,362 @@ +"""One threshold test at every classification gate (#417). + +Similarity scores are floats, so a score can print as its threshold and still +sit just under it: ``0.7 + 0.1`` is ``0.7999999999999999``. A primitive list +element was classified with ``ThresholdHelper.is_above_threshold``, which +accepts a score up to ``1e-10`` under the threshold, while a field, a nested +model and a ``List[StructuredModel]`` pair were classified with a bare ``>=``. +The same score was then a TP in one place and an FD in another. + +Each gate below is checked at four scores: one float rounding error under the +threshold, exactly at it, just outside the tolerance, and clearly under it. +""" + +from typing import List, Optional + +import pytest + +import stickler +from stickler import ( + ComparableField, + ExactComparator, + LevenshteinComparator, + StructuredModel, +) +from stickler.algorithms.hungarian import HungarianMatcher +from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.comparison_info import ( + ComparableFieldConfig, + ComparisonInfo, +) +from stickler.structured_object_evaluator.models.metrics_helper import MetricsHelper +from stickler.structured_object_evaluator.models.threshold_helper import ( + ThresholdHelper, +) + +THRESHOLD = 0.8 + +# 0.7 + 0.1 is 0.7999999999999999 in IEEE 754 doubles, 1.1e-16 under 0.8. +NEAR = 0.7 + 0.1 + +# Just outside the 1e-10 tolerance, so still under the threshold. +OUTSIDE = THRESHOLD - 1e-9 + +# (score, whether it meets THRESHOLD) +CASES = [ + pytest.param(NEAR, True, id="float-error-under"), + pytest.param(THRESHOLD, True, id="at-threshold"), + pytest.param(OUTSIDE, False, id="outside-tolerance"), + pytest.param(0.79, False, id="clearly-under"), +] + + +class _FixedScore(BaseComparator): + """Scores equal values 1.0 and every other pair at ``score``.""" + + def __init__(self, score: float, threshold: Optional[float] = None): + super().__init__(threshold=threshold) + self.score = score + + def _compare(self, str1, str2) -> float: + return 1.0 if str1 == str2 else self.score + + +def _counts(node: dict) -> tuple: + overall = node["overall"] + return overall["tp"], overall["fd"] + + +def _expected_counts(matches: bool) -> tuple: + return (1, 0) if matches else (0, 1) + + +def _full_result(gt: StructuredModel, pred: StructuredModel) -> dict: + return gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + + +def _non_match_paths(result: dict) -> list: + return [entry["field_path"] for entry in result["non_matches"]] + + +def _comparison_rows(result: dict) -> dict: + return {row["expected_key"]: row["match"] for row in result["field_comparisons"]} + + +def _flat_model(score: float): + class Flat(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=THRESHOLD) + + return Flat + + +def _list_item_models(score: float): + """A list item whose ``name`` sub-field scores ``score``. + + ``key`` matches exactly and ``match_threshold`` is low, so the pair always + matches as an object and only the sub-field sits at the boundary. + """ + + class Item(StructuredModel): + key: str = ComparableField(comparator=ExactComparator(), threshold=1.0) + name: str = ComparableField(comparator=_FixedScore(score), threshold=THRESHOLD) + match_threshold = 0.5 + + class Holder(StructuredModel): + items: List[Item] = ComparableField() + + return Item, Holder + + +def test_the_premise(): + """Guard the inputs, so the tests below mean what they say.""" + assert NEAR < THRESHOLD + assert ThresholdHelper.is_above_threshold(NEAR, THRESHOLD) + assert not ThresholdHelper.is_above_threshold(OUTSIDE, THRESHOLD) + + +class TestFieldGate: + """A top-level primitive field, scored by ``FieldComparator``.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert _counts(result["confusion_matrix"]["fields"]["name"]) == ( + _expected_counts(matches) + ) + + @pytest.mark.parametrize("score,matches", CASES) + def test_only_a_miss_is_clipped(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert result["field_scores"]["name"] == (score if matches else 0.0) + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert _non_match_paths(result) == ([] if matches else ["name"]) + assert _comparison_rows(result) == {"name": matches} + + +class TestNestedModelGate: + """A nested ``StructuredModel`` field, classified on its object score.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts_and_score(self, score, matches): + Inner = _flat_model(score) + + class Outer(StructuredModel): + inner: Inner = ComparableField(threshold=THRESHOLD) + + gt, pred = Outer(inner=Inner(name="a")), Outer(inner=Inner(name="b")) + assert gt.inner.compare(pred.inner) == score + + result = _full_result(gt, pred) + assert _counts(result["confusion_matrix"]["fields"]["inner"]) == ( + _expected_counts(matches) + ) + assert result["field_scores"]["inner"] == (score if matches else 0.0) + + +class TestListObjectGate: + """A ``List[StructuredModel]`` pair against the element's ``match_threshold``.""" + + @staticmethod + def _models(score: float): + class Item(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=0.5) + match_threshold = THRESHOLD + + class Holder(StructuredModel): + items: List[Item] = ComparableField() + + return Item, Holder + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts_and_recursion(self, score, matches): + Item, Holder = self._models(score) + result = _full_result( + Holder(items=[Item(name="a")]), Holder(items=[Item(name="b")]) + ) + items = result["confusion_matrix"]["fields"]["items"] + assert _counts(items) == _expected_counts(matches) + # A matched pair is descended into; a pair below the gate is not. + assert ("name" in items["fields"]) is matches + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Item, Holder = self._models(score) + result = _full_result( + Holder(items=[Item(name="a")]), Holder(items=[Item(name="b")]) + ) + assert _non_match_paths(result) == ([] if matches else ["items[0]"]) + if matches: + assert _comparison_rows(result) == {"items[0].name": True} + else: + assert _comparison_rows(result) == {"items[0]": False} + + def test_the_documented_worked_example(self): + """The scenarios and result block in ``threshold-gated-evaluation.md``.""" + + class Product(StructuredModel): + product_id: str = ComparableField( + comparator=ExactComparator(), threshold=1.0, weight=3.0 + ) + name: str = ComparableField( + comparator=LevenshteinComparator(), threshold=0.7, weight=2.0 + ) + price: float = ComparableField(threshold=0.9, weight=1.0) + match_threshold = 0.8 + + class Order(StructuredModel): + order_id: str = ComparableField( + comparator=ExactComparator(), threshold=1.0, weight=2.0 + ) + products: List[Product] = ComparableField(weight=3.0) + + gt = [ + Product(product_id="PROD-001", name="Laptop", price=999.99), + Product(product_id="PROD-002", name="Mouse", price=29.99), + Product(product_id="PROD-003", name="Cable", price=14.99), + ] + pred = [ + Product(product_id="PROD-001", name="Laptop Computer", price=999.99), + Product(product_id="PROD-002", name="Different Product", price=99.99), + Product(product_id="PROD-004", name="New Product", price=19.99), + ] + assert gt[0].compare(pred[0]) == NEAR + + def run(gt_items, pred_items): + return _full_result( + Order(order_id="ORD-1", products=gt_items), + Order(order_id="ORD-1", products=pred_items), + ) + + result = run(gt, pred) + products = result["confusion_matrix"]["fields"]["products"] + overall = products["overall"] + assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == [1, 2, 0, 0] + assert overall["derived"]["cm_precision"] == pytest.approx(1 / 3) + assert overall["derived"]["cm_recall"] == 1.0 + assert overall["derived"]["cm_f1"] == pytest.approx(0.5) + assert _counts(products["fields"]["product_id"]) == (1, 0) + assert _counts(products["fields"]["name"]) == (0, 1) + assert _counts(products["fields"]["price"]) == (1, 0) + assert [ + (entry["field_path"], entry["non_match_type"], round(entry["similarity_score"], 4)) + for entry in result["non_matches"] + ] == [ + ("products[0].name", "false_discovery", 0.4), + ("products[1]", "false_discovery", 0.6725), + ("products[2]", "false_discovery", 0.1333), + ] + + # Only lists of different lengths leave an item unmatched. + for gt_items, pred_items, kind, counts in ( + (gt, pred[:2], "false_negative", [1, 1, 1, 0]), + (gt[:2], pred, "false_alarm", [1, 1, 0, 1]), + ): + result = run(gt_items, pred_items) + overall = result["confusion_matrix"]["fields"]["products"]["overall"] + assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == counts + last = result["non_matches"][-1] + assert (last["field_path"], last["non_match_type"]) == ("products[2]", kind) + + +class TestListSubFieldGate: + """A primitive sub-field of a matched ``List[StructuredModel]`` pair.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts(self, score, matches): + Item, Holder = _list_item_models(score) + result = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + ) + name = result["confusion_matrix"]["fields"]["items"]["fields"]["name"] + assert _counts(name) == _expected_counts(matches) + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Item, Holder = _list_item_models(score) + result = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + ) + assert _non_match_paths(result) == ([] if matches else ["items[0].name"]) + assert _comparison_rows(result) == { + "items[0].key": True, + "items[0].name": matches, + } + + @pytest.mark.parametrize("score,matches", CASES) + def test_agrees_with_a_field_and_a_list_element(self, score, matches): + """The same score and threshold give one verdict wherever they meet.""" + Item, Holder = _list_item_models(score) + sub_field = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + )["confusion_matrix"]["fields"]["items"]["fields"]["name"] + + Flat = _flat_model(score) + field = _full_result(Flat(name="a"), Flat(name="b"))["confusion_matrix"][ + "fields" + ]["name"] + + class Names(StructuredModel): + names: List[str] = ComparableField( + comparator=_FixedScore(score), threshold=THRESHOLD + ) + + element = _full_result(Names(names=["a"]), Names(names=["b"]))[ + "confusion_matrix" + ]["fields"]["names"] + + expected = _expected_counts(matches) + assert _counts(sub_field) == _counts(field) == _counts(element) == expected + + +class TestObjectVerdict: + """``EvalResult.matched`` reads the same ``match_threshold`` as list pairing.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_matched(self, score, matches): + class Flat(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=0.5) + + result = stickler.evaluate( + Flat(name="a"), Flat(name="b"), match_threshold=THRESHOLD + ) + assert result.overall_score == score + assert result.matched is matches + + +class TestStandaloneGates: + @pytest.mark.parametrize("score,matches", CASES) + def test_hungarian_matcher_counts(self, score, matches): + matcher = HungarianMatcher(_FixedScore(score), match_threshold=THRESHOLD) + metrics = matcher.calculate_metrics(["a"], ["b"]) + assert (metrics["tp"], metrics["fd"]) == _expected_counts(matches) + + @pytest.mark.parametrize("score,matches", CASES) + def test_binary_metrics(self, score, matches): + """The fallback ``evaluator_format=True`` uses without a confusion matrix.""" + metrics = MetricsHelper().convert_score_to_binary_metrics(score, THRESHOLD) + assert metrics["recall"] == (1.0 if matches else 0.0) + + @pytest.mark.parametrize("score,matches", CASES) + def test_comparator_and_field_config(self, score, matches): + """``binary_compare`` and the field configs' clipping ``compare``.""" + comparator = _FixedScore(score, threshold=THRESHOLD) + assert comparator.binary_compare("a", "b") == ((1, 0) if matches else (0, 1)) + + kept = score if matches else 0.0 + for config_cls in (ComparisonInfo, ComparableFieldConfig): + config = config_cls(_FixedScore(score), threshold=THRESHOLD) + assert config.compare("a", "b") == kept diff --git a/tests/test_list_reporting.py b/tests/test_list_reporting.py index bd101c64..f2ef10f6 100644 --- a/tests/test_list_reporting.py +++ b/tests/test_list_reporting.py @@ -504,7 +504,7 @@ class Parent(StructuredModel): (row,) = result["field_comparisons"] assert row["match"] is True assert row["score"] == 0.7 - 1e-12 - assert row["reason"] == f"all elements matched (score {row['score']!r} < 0.7)" + assert row["reason"] == f"within threshold tolerance ({row['score']:.12g} vs 0.7)" def test_structured_child_custom_compare_with_override_is_preserved(): @@ -529,7 +529,7 @@ class Parent(StructuredModel): assert result["non_matches"] == [] -def test_accepted_structured_child_scalar_threshold_is_still_exact(): +def test_accepted_structured_child_scalar_threshold_shares_the_tolerance(): class NearThresholdComparator(BaseComparator): def _compare(self, left, right): return 0.7 - 1e-12 @@ -547,9 +547,9 @@ class Parent(StructuredModel): result = report([Item(code="a")], [Item(code="b")], model=Parent) child = result["confusion_matrix"]["fields"]["items"]["fields"]["code"] - assert child["overall"]["fd"] == 1 - assert result["non_matches"][0]["field_path"] == "items[0].code" - assert result["field_comparisons"][0]["match"] is False + assert child["overall"]["tp"] == 1 + assert result["non_matches"] == [] + assert result["field_comparisons"][0]["match"] is True def test_nested_compare_recursive_override_keeps_its_original_signature():