Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low, optional. RELEASING.md ("What belongs in the changelog") says entries are for changes a user can observe, and "When in doubt, ask whether a user reading the release notes could act on it." This entry corrects a table in the 1.0.0 notes, which is defensible. But the user-facing correction in this PR, the mean_score sentence in bulk-evaluation.md and understanding-results.md (leaves under a list get no score, object nodes inside an element do), has no entry. If one of the two gets an entry, the guide-page correction is the one a user can act on.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the guide fix is the one a user can act on. I added an Unreleased Documentation entry for it (#249) and kept the #338 table correction next to it. Fixed in 18c241d.

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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Guides/Evaluation/bulk-evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Guides/Evaluation/understanding-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1162,41 +1162,82 @@ 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(
comparator=LevenshteinComparator(), weight=5.0
)
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (recall). The corrected bare row (now = 0.5) and the [Plain] vs [Plain] = 0.0 claim in the prose below are not asserted by any test in this class. #338 happened because the table numbers were unpinned and drifted from behaviour; this edit leaves them unpinned again. I measured on 12135c6: bare [Plain, NoteA] vs [Plain, NoteB] = 0.5 (tp=1, fd=1), bare [Plain] vs [Plain] = 0.0. Suggest a test such as test_the_bare_row_loses_the_refused_plain_pair asserting self._score(self._bare(), (self.Plain(sku="p"),)) is 0.0 and the bare mixed pair is 0.5, so the next drift fails CI.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point; leaving it unpinned is how #338 happened. Added test_the_bare_row_loses_the_refused_plain_pair: [Plain] alone is 0.0, and bare [Plain, NoteA] vs [Plain, NoteB] is 0.5 with tp=1, fd=1. It fails on both 6cbcc74 and 1c4b28f. Fixed in 18c241d.

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):
Expand Down Expand Up @@ -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`.

Expand Down
Loading