diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c99b8e8..52509832 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -342,6 +342,30 @@ Each release links to full notes on the characters. Present since 0.1.3 ([#431](https://github.com/awslabs/stickler/issues/431)) +### Documentation + +- Corrected which paths in `BulkStructuredModelEvaluator` `field_metrics` get a + `mean_score`. The guides said `compare_with()` scores only the list parent of a + `List[StructuredModel]`. A list element's own `StructuredModel` and + `List[StructuredModel]` fields (`items.addr`, `items.parts`) are scored too, + but each document's value is its first matched element pair's score, not a + mean over pairs, so it depends on element order + ([#428](https://github.com/awslabs/stickler/issues/428)). Every other path + inside an element (`items.name`, `items.tags`, `items.addr.city`, + `items.addr.geo`, a plain `BaseModel` field) carries confusion-matrix counts + but no `mean_score`. All of them count only element pairs that met the + match threshold: a pair below it emits no element fields at all. Scoring is + unchanged ([#249](https://github.com/awslabs/stickler/issues/249)) + +- Corrected the last row of the 1.0.0 table under "The element gate judges a + PAIR, not a list". Under its bare `Optional[List[Any]]` heading, + `[Plain, NoteSM]` vs `[Plain, Note2SM]` scores `0.5`, not `1.0`, and scored + `0.0`, not `0.5`, under the list-wide gate. The published `1.0`, `0.5`, `1.0` + hold only with a comparator declared on `f`. The bare `0.5` is the refused + `Plain` pair (`[Plain]` vs `[Plain]` scores `0.0` bare), not the cross-class + rule. Scoring is unchanged + ([#338](https://github.com/awslabs/stickler/issues/338)) + ## [1.0.0] - 2026-09-11 ### Added diff --git a/docs/docs/Guides/Evaluation/bulk-evaluation.md b/docs/docs/Guides/Evaluation/bulk-evaluation.md index 68ee2c8a..8ec3cf1a 100644 --- a/docs/docs/Guides/Evaluation/bulk-evaluation.md +++ b/docs/docs/Guides/Evaluation/bulk-evaluation.md @@ -139,7 +139,7 @@ Because each document's `overall_score = Σ_f(score × weight) / Σ_f(weight)` a The denominator is the count of documents whose `overall_score` was a finite number: error docs (`update()` raised) and successful docs carrying a non-finite or missing `overall_score` are both excluded. With zero eligible documents the score is `0.0` — disambiguate via `document_count` when that matters. -Per-field `mean_score` is reported at every nested path (leaf and object/list aggregate) where `threshold_applied_score` was observed in at least one document, averaging over just those documents. Paths with confusion-matrix counts but no score data (e.g., leaves inside `List[StructuredModel]`, where `compare_with()` only emits the score at the list parent) are surfaced without a `mean_score` key rather than reported as `0.0`. +Per-field `mean_score` is reported at every nested path (leaf and object/list aggregate) where `threshold_applied_score` was observed in at least one document, averaging over just those documents. Paths with confusion-matrix counts but no score data are surfaced without a `mean_score` key rather than reported as `0.0`. Inside a `List[StructuredModel]` element, only the element's own `StructuredModel` and `List[StructuredModel]` fields (`items.addr`, `items.parts`) are scored, and each document's value is its first matched element pair's score, not a mean over pairs, so it depends on element order ([#428](https://github.com/awslabs/stickler/issues/428)). Every other path inside an element (`items.name`, `items.tags`, `items.addr.city`, `items.addr.geo`) has counts only. All of them count only element pairs that met the match threshold: `compare_with()` emits no element fields for a pair below it. --- diff --git a/docs/docs/Guides/Evaluation/understanding-results.md b/docs/docs/Guides/Evaluation/understanding-results.md index 8e7334a3..24fd500a 100644 --- a/docs/docs/Guides/Evaluation/understanding-results.md +++ b/docs/docs/Guides/Evaluation/understanding-results.md @@ -402,7 +402,7 @@ This is useful for comprehensive auditing of all comparisons, not just failures. The per-document `overall_score` above is a weighted average of field scores. When you aggregate across many documents with `BulkStructuredModelEvaluator.compute()`, the weight information is preserved via two keys: - **`metrics["weighted_overall_score"]`** (float) -- Arithmetic mean of each document's `overall_score`. Prefer this over `cm_f1` whenever your schema uses non-uniform `ComparableField(weight=...)` values: `cm_f1` treats every field-match equally, while `weighted_overall_score` preserves the declared per-field weights across the dataset. -- **`field_metrics[path]["mean_score"]`** (float, when present) -- Arithmetic mean of each document's `threshold_applied_score` at that path, reported at every nested node that was actually scored. Paths with confusion-matrix counts but no score data (e.g., leaves inside `List[StructuredModel]`, where `compare_with()` only emits the score at the list parent) are surfaced without a `mean_score` key rather than as `0.0`. +- **`field_metrics[path]["mean_score"]`** (float, when present) -- Arithmetic mean of each document's `threshold_applied_score` at that path, reported at every nested node that was actually scored. Paths with confusion-matrix counts but no score data are surfaced without a `mean_score` key rather than as `0.0`. Inside a `List[StructuredModel]` element, only the element's own `StructuredModel` and `List[StructuredModel]` fields (`items.addr`, `items.parts`) are scored, and each document's value is its first matched element pair's score, not a mean over pairs, so it depends on element order ([#428](https://github.com/awslabs/stickler/issues/428)). Every other path inside an element (`items.name`, `items.tags`, `items.addr.city`, `items.addr.geo`) has counts only. All of them count only element pairs that met the match threshold: `compare_with()` emits no element fields for a pair below it. ```python from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( diff --git a/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py b/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py index 9d99fab3..efc5cb80 100644 --- a/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py +++ b/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py @@ -456,10 +456,19 @@ def _accumulate_field_metrics( ) -> None: """Recursively accumulate field-level CM counts and threshold_applied_score. - Walks both ``fields`` (object subtrees) and ``nested_fields`` - (list-of-StructuredModel) so per-field ``mean_score`` is recorded - at every node compare_with emits, including leaves under list - parents. + Walks ``fields``, which holds both object subtrees and the element + fields of a list of StructuredModel, so CM counts are recorded at + every node compare_with emits. Score sums (for ``mean_score``) are + recorded only where a node carries a finite + ``threshold_applied_score``. Inside a list element, only the + element's own StructuredModel and list-of-StructuredModel fields + (``items.addr``, ``items.parts``) carry one, copied from the first + matched element pair. Every other path inside an element (leaves, + primitive lists, ``items.addr.geo``) carries CM counts only, so it + gets no ``mean_score`` (see #249). An element pair below the match + threshold emits no element fields, so every path inside an element + counts matched pairs only. + ``nested_fields`` is also walked, but compare_with no longer emits it. """ for field_name, field_data in fields_dict.items(): if not isinstance(field_data, dict): diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper.py b/src/stickler/structured_object_evaluator/models/comparison_helper.py index a1a99235..4b8da41e 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper.py @@ -50,16 +50,21 @@ class _ClassGatedComparator(BaseComparator): [{'a':1},{'b':2},{'c':3}] 1.0 1.0 [{'a':1},{'b':2},{'c':3}, Plain('p')] 1.0 0.0 <- fd on all four [NoteSM] vs [Note2SM] 1.0 1.0 - [Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.5 + [Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.0 + same, with a comparator declared on `f` 1.0 0.5 The dict row zeroed three elements that score 1.0 on their own, in the same list, on `dev`, and here the moment the plain model is removed -- and it drew a "holds a mapping" warning on a field whose annotation says nothing about - mappings. The `StructuredModel` row is worse than wrong-looking: it enforces - the cross-class rule that #327 is explicitly holding open, so a user got the - #327 answer or the documented one according to whether an unrelated plain - model shared the list. Both rules now apply to exactly the population the - wrapper was installed for. + mappings. The two `[Plain, NoteSM]` rows are worse than wrong-looking: both + enforce the cross-class rule that #327 is explicitly holding open (the bare + row's 0.0 is fd=2, the refused `Plain` pair plus `NoteSM`/`Note2SM`; with + `[Plain, NoteSM]` on both sides it scores 0.5), so a user got the #327 answer + or the documented one according to whether an unrelated plain model shared + the list. Both rules now apply to exactly the population the wrapper was + installed for. The declared row now scores 1.0; the bare row scores 0.5, + because the bare annotation still refuses the `Plain` pair on its own + (`[Plain]` vs `[Plain]` scores 0.0), not because of the cross-class rule. A dict element does not reach the gate -- neither because `_holds_a_plain_model` does not look for one, which was the old and only diff --git a/tests/structured_object_evaluator/test_bulk_structured_model_evaluator.py b/tests/structured_object_evaluator/test_bulk_structured_model_evaluator.py index c31373b6..aac5843f 100644 --- a/tests/structured_object_evaluator/test_bulk_structured_model_evaluator.py +++ b/tests/structured_object_evaluator/test_bulk_structured_model_evaluator.py @@ -1162,17 +1162,40 @@ def test_score_only_path_surfaces_in_field_metrics(self): assert result.field_metrics["bar"].get("tp", 0) == 0 def test_list_of_model_leaf_omits_mean_score_key(self): - """Leaves inside List[StructuredModel] get CM counts but no mean_score. - - compare_with() only emits threshold_applied_score at the list parent, - so nested leaves never accumulate a score. The key is omitted rather - than reported as a misleading 0.0. + """In a List[StructuredModel] element only its own StructuredModel and + List[StructuredModel] fields get mean_score. + + compare_with() scores the list parent and those fields (``items.addr``, + ``items.parts``), copied from the first matched pair (#428), but emits + every other path inside an element without threshold_applied_score: + leaves, primitive lists, a plain BaseModel field, and anything two levels + down (``items.addr.geo``, ``items.parts.sku``). Those get CM counts only, + and the key is omitted rather than reported as a misleading 0.0 (#249). """ from typing import List as _List + from pydantic import BaseModel + + class _Geo(StructuredModel): + lat: str = ComparableField(comparator=LevenshteinComparator()) + + class _Addr(StructuredModel): + city: str = ComparableField(comparator=LevenshteinComparator()) + geo: _Geo = ComparableField() + + class _Part(StructuredModel): + sku: str = ComparableField(comparator=LevenshteinComparator()) + + class _Plain(BaseModel): + note: str + class _Line(StructuredModel): name: str = ComparableField(comparator=LevenshteinComparator(), weight=2.0) qty: int = ComparableField(comparator=NumericComparator(), weight=1.0) + tags: _List[str] = ComparableField() + addr: _Addr = ComparableField() + parts: _List[_Part] = ComparableField() + plain: _Plain = ComparableField() class _Order(StructuredModel): order_id: str = ComparableField( @@ -1180,23 +1203,41 @@ class _Order(StructuredModel): ) items: _List[_Line] = ComparableField(weight=3.0) - gt = _Order(order_id="O-1", items=[_Line(name="apple", qty=1)]) - pred = _Order(order_id="O-1", items=[_Line(name="apple", qty=1)]) + line = _Line( + name="apple", + qty=1, + tags=["red"], + addr=_Addr(city="Oslo", geo=_Geo(lat="59.9")), + parts=[_Part(sku="A-1")], + plain=_Plain(note="n"), + ) + gt = _Order(order_id="O-1", items=[line]) + pred = _Order(order_id="O-1", items=[line]) evaluator = BulkStructuredModelEvaluator(target_schema=_Order) evaluator.update(gt, pred) evaluator.update(gt, pred) - result = evaluator.compute() - - # Nested leaves get CM counts bubbled up... - assert "items.name" in result.field_metrics - assert result.field_metrics["items.name"].get("tp", 0) > 0 - # ...but no mean_score because compare_with emits it only at the parent. - assert "mean_score" not in result.field_metrics["items.name"] - assert "mean_score" not in result.field_metrics["items.qty"] - # List parent and sibling leaves do surface mean_score. - assert "mean_score" in result.field_metrics["items"] - assert "mean_score" in result.field_metrics["order_id"] + fm = evaluator.compute().field_metrics + + unscored = ( + "items.name", + "items.qty", + "items.tags", + "items.addr.city", + "items.addr.geo", + "items.addr.geo.lat", + "items.plain", + "items.parts.sku", + ) + for path in unscored: + # CM counts bubble up... + assert fm[path].get("tp", 0) > 0, path + # ...but compare_with emits these paths unscored. + assert "mean_score" not in fm[path], path + # The list parent, the element's own StructuredModel and + # List[StructuredModel] fields, and top-level leaves do surface mean_score. + for path in ("items", "items.addr", "items.parts", "order_id"): + assert "mean_score" in fm[path], path def test_invalid_overall_score_skipped(self): """Non-numeric, non-finite, and bool overall_score are silently dropped. diff --git a/tests/structured_object_evaluator/test_nested_plain_basemodel.py b/tests/structured_object_evaluator/test_nested_plain_basemodel.py index 37d5e5e7..91f7358c 100644 --- a/tests/structured_object_evaluator/test_nested_plain_basemodel.py +++ b/tests/structured_object_evaluator/test_nested_plain_basemodel.py @@ -1707,14 +1707,18 @@ class TestTheElementGateJudgesAPairNotAList: [{'a':1},{'b':2},{'c':3}, Plain('p')] 1.0 0.0 0.75 ['x','y','z', Plain('p')] 1.0 0.75 0.75 [NoteSM] vs [Note2SM] 1.0 1.0 1.0 - [Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.5 1.0 + [Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.0 0.5 + same, comparator declared on `f` 1.0 0.5 1.0 The string row is the shape the refusal is FOR: one element out of four cannot be scored, and the field loses a quarter. The dict row zeroed three elements that score 1.0 on their own, in the same list, on `dev`, and here the moment - the plain model is removed. The last row enforced the cross-class rule that - #327 is deliberately holding open, so the answer depended on whether an - unrelated plain model shared the list. + the plain model is removed. Both `[Plain, NoteSM]` rows enforced the + cross-class rule that #327 is deliberately holding open (bare: fd=2 under the + list-wide gate), so the answer depended on whether an unrelated plain model + shared the list. The bare row's 0.5 now is the refused `Plain` pair + (`[Plain]` vs `[Plain]` scores 0.0 bare), not that rule, which is why + `test_two_structured_model_classes_keep_the_declared_gap` uses `Declared`. """ class Plain(BaseModel): @@ -1800,6 +1804,23 @@ def test_two_structured_model_classes_keep_the_declared_gap(self): assert alone == pytest.approx(1.0) assert beside_a_plain_model == pytest.approx(alone) + def test_the_bare_row_loses_the_refused_plain_pair(self): + """Pins the bare `[Plain, NoteSM]` row of the table above (#338). + + The row drifted from behaviour once because nothing asserted it. The bare + 0.5 is the refused `Plain` pair: `[Plain]` alone scores 0.0, and the + cross-class `NoteA`/`NoteB` pair still scores as a match (tp=1). + """ + Bare = self._bare() + assert self._score(Bare, (self.Plain(sku="p"),)) == pytest.approx(0.0) + result = Bare(f=[self.Plain(sku="p"), self.NoteA(sku="a")]).compare_with( + Bare(f=[self.Plain(sku="p"), self.NoteB(sku="a")]), + include_confusion_matrix=True, + ) + node = result["confusion_matrix"]["fields"]["f"]["overall"] + assert result["field_scores"]["f"] == pytest.approx(0.5) + assert (node["tp"], node["fd"]) == (1, 1) + def test_a_plain_model_against_a_structured_model_is_still_a_mismatch(self): """The pair `and` would have waved through, which is why the rule reads `or`.