Repository navigation
fix(400): classify a list element's sub-field through the top-level dispatcher - #406
Conversation
…atcher `_handle_non_hierarchical_field` counted each matched pair's primitive sub-field by calling the field's comparator directly, skipping the guards `_dispatch_field_comparison` applies. A dict in an `Any` sub-field of a list item raised `TypeError` out of `compare_with()`, where the same field at top level warns and scores an FD. Route it through the dispatcher, as the hierarchical and simple-list branches already do, so the counts agree with the top-level path by construction. Counts also move, but not scores: with an inferred comparator, a tuple, set or `date` vs ISO string is an FD, not a TP; a list in an `Any` sub-field counts one per element; and a whitespace-only string is a value, not null. Closes #400.
The crash is not Any-only: a Union sub-field, or a Dict one with an explicit LevenshteinComparator, raised too. bytes, arbitrary objects and plain pydantic models under a refused comparator also moved from TP to FD. Adds those cases, a whitespace-vs-None case, and a check that the counts now agree with non_matches.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-18T16:17:55+00:00 |
…st-item # Conflicts: # CHANGELOG.md
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
Measured on the merge base 251f333, head 3145138, and head merged into dev 52e8ef4. On the merged tree the full suite passes (3968 passed). The ! is justified, because list-element sub-field counts change for the same input. Blockers are inline:
structured_list_comparator.py:546: a list holding more than one model class raisesAttributeError. The crash predates this PR, but the PR adds a new path to it, and the new docs say list elements follow the top-level rules, which do not raise.structured_list_comparator.py:553: for anAnysub-field, null vs[]moves from TN to FA/FN, and[]vs[]produces no count.structured_list_comparator.py:553, same line: a wrong-class prediction in aUnionsub-field moves from FD to TP. The cause is infield_comparator.py:136, outside the diff.structured_list_comparator.py:555:aggregatedrops thefieldssubtree, so it still differs from the top level.CHANGELOG.md:97andclassification-logic.md:201under-state the count changes.test_list_item_subfield_parity.py:110: the parity test cannot fail.
| @@ -546,9 +546,13 @@ def _handle_non_hierarchical_field( | |||
| gt_sub_value = getattr(gt_item, sub_field_name) | |||
There was a problem hiding this comment.
Blocker: a list holding more than one model class raises AttributeError.
Sub-field names come from the class of gt_list[0] (lines 287-300) and are read with a bare getattr.
pets: List[Pet] with GT and prediction both [Cat(name='tom', lives=9), Pet(name='rex')] raises AttributeError: 'Pet' object has no attribute 'lives'. A perfect List[Union[Search, Browse]] prediction raises the same way. The top level uses getattr(other, name, None) (comparison_engine.py:166) and does not raise.
The crash predates this PR, but the PR adds a new path to it. An element class that overrides compare_with, with an Any sub-field holding [Inner(a='x')] vs [{'a':'x'}], now raises through line 553, where the merge base counted 1 FD. The same bare getattr is at lines 349-350 and 526-527. Use getattr(..., None), as the top level does.
There was a problem hiding this comment.
Thanks, good catch. Fixed in 2c43b0e. The three bare getattrs are now one loop, _dispatch_pairs, which reads both values with getattr(..., None) as top level does. Each pair is classified on the fields its own GT element declares. Your [Cat(tom, 9), Pet(rex)] and perfect List[Union[Search, Browse]] repros both score 1.0 now, and lives counts 1 TP, for the Cat pair only (992fc09). With the base class first, [Pet(rex), Cat(tom, 9)] vs [Pet(rex), Pet(tom)] ran before and counted only name (2 TP). It now also counts lives as 1 FN. The score is 0.75 on both (f98703e).
[Inner(a="x")] vs [{"a": "x"}] in an Any sub-field no longer raises either. With an element compare_with() that returns a fixed score, as yours did, dev counted 1 FD. It is now a TP with 1 FN and 1 TN under aggregate, which is what the same field counts without the override and at top level. The same holds with that override against a list of strings, numbers, lists or other dicts, and in an object sub-field. It also holds against [Other(c="z")], which was an FD at a field threshold of 0.9. At the default threshold that pair was already a TP, and only its aggregate moves. Without an override, or with one that calls super().compare_with, these inputs already raised on current dev. a9a9542 and 5dc6c0e pin them, and the CHANGELOG names them all (e34e9b8). Those TPs stay, as for the other pairs of different classes, until StructuredModel follows the different-classes rule (#327).
Two shapes under that override still count as on dev, 1 FD at score 1.0: a list of models against plain pydantic models, such as [Inner(a="x")] vs [Point(x=1)], and a GT list holding a value without compare_with(), such as [Inner(a="x"), "b"] vs ["a", "b"]. The dispatcher raises on both, as it does at top level and without the override, and an earlier head of this PR raised on them. 15ffdc2 counts them from the field's comparator again when the dispatcher raises on two lists in a sub-field read by value. Only an element whose compare_with() doesn't recurse gets there, since scoring the element otherwise raises first. 57d5c1c pins them, and the CHANGELOG names them (cd3fb59). The same fallback covers a list-annotated sub-field, such as List[Any], that the list's first element's class doesn't declare as a list, since dev read only that class's fields. A fixed-score subclass's List[Any] field listed after its base now counts 1 FD for [Inner(a="x"), "b"] against ["a", "b"], where dev didn't count it, and a union class's Optional[List[Any]] field after a str-typed first element counts 1 FD, as on dev. If the first element's pair isn't a match, each pair is read by its own class. Scores match dev in every case (b9ab522, pinned in c8e5d72, CHANGELOG in efa47ca). Under that override, a sub-field now also gets the dispatcher's warnings, as it does without the override and at top level. A dict or plain pydantic model its comparator can't score, or a plain pydantic model against a model of another class, warns where dev was silent, so a run with warnings as errors raises there. The CHANGELOG says so (a5e8aa0, 9ab8ec9), and f1aa451 and dfc5cc1 pin it.
The same crash hit a list of models in an Any, object or List[Any] field, at top level too, against a list of strings, numbers, dicts or lists, or against a list holding a model of another class, such as [Inner(a="x")] vs [Other(c="z")]. Those run now, and f98703e and e414a7c pin them.
One side effect to flag. Some pairs the old code crashed on now count a TP that their score doesn't credit. In List[Union[Search, Browse]], [Search(query="hotels")] vs [Browse(url="x.com")] is an object-level TP, with query 1 FN under aggregate, while the field scores 0.0. A model against a non-model element, such as [Inner(a="x")] vs ["a"] in an Any field, pairs as a TP the same way. A plain pydantic element is the exception: scoring a model against it raises TypeError, at top level too, as on dev (f32912a). The pairing verdict comes from compare(), which skips the fields the prediction lacks. That's the #327 gap, so I'd rather fix it there than add a list-only rule. The CHANGELOG and the different-classes warning in classification-logic.md say so, and f98703e pins both.
The ground-truth side still raises in one shape, as on dev. When the first GT element is a model, the list is scored as a list of models, which calls each matched GT element's compare_with(). So [Inner(a="x"), "b"] against itself fails on the string's missing compare_with(), and a number or a dict in its place fails the same way. ["b", Inner(a="x")] against itself runs, and so does [Inner(a="x"), "b"] against [Inner(a="x")], where the string goes unmatched. 1269607 pins all of these, and the CHANGELOG names the raise. A non-model element with its own compare_with(), such as a plain pydantic model, used to raise as well. e40c334 leaves it out of field classification, so [Inner(a="x"), Scored()] against itself now scores 1.0 with value 2 TP, and the CHANGELOG names that fix (f39c15f). Its verdict comes from the pairing, not from that compare_with(), so one that returns 0.0 also counts a TP. That is tracked as a follow-up for 1.1.0.
| # a sub-field counts the way it does outside a list. Calling the | ||
| # comparator directly skipped its guards, so a dict it cannot | ||
| # score raised instead of scoring an FD (#400). | ||
| field_classification = gt_item._dispatch_field_comparison( |
There was a problem hiding this comment.
Blocker: routing through the dispatcher changes empty-list counts, and wrong-class predictions now count as TP.
Empty lists. For Element.value: Any inside Holder.items: List[Element]:
Nonevs[]moves from TN to FA.[]vsNonemoves from TN to FN.'',{}or NaN vs[]moves from TN to FA.[]vs[]and[None]vs[None]move from TN to no count at all.
This contradicts classification-logic.md lines 41, 56 and 193. Dispatcher STEP 3 applies list null handling only when the annotation is a list. STEP 4 does not treat [] as null. PrimitiveListComparator hard-codes tn: 0.
Wrong-class predictions. A StructuredModel in an Any/Union sub-field is now judged by compare() (dispatcher CASE 3, field_comparator.py:136) instead of by compare_with()['overall_score']. With value: Union[Search, Browse] = ComparableField(threshold=0.9), a GT Search(...) against a predicted Browse(...) moves from FD to TP, while non_matches still reports items[0].value.query as a false negative. #327 (classification-logic.md:125) says different classes are always FD. Inner(a, b) vs Other(c) also becomes TP, because compare() returns 1.0 when the two share no field.
There was a problem hiding this comment.
Agreed on both, thanks.
Empty lists. In a sub-field the list path reads by value, such as Any, object or Sequence[str], the list path reads an empty list as null by its value (2c43b0e, scoped in 0a52737). Every row you listed is a TN again: None, "", {} or NaN vs [], [] vs None, [] vs [], and [None] vs [None]. "x" vs [] is an FN. All of these are as on dev, and 992fc09 pins them. One kind of row against [] does move. A value top level doesn't read as null, such as " ", (), frozenset() or b" ", is not null here either, so " " vs [] is now an FN (the reverse an FA), not a TN, as it is against None, "", {} or NaN. The CHANGELOG gives it as an example of the rule, and bfea4ad and 776449e pin it. When both sides are lists, they still go to the list comparator, which counts one per element. Sub-fields annotated as a list, such as List[str] or Union[str, List[str]], go straight to the dispatcher, as on dev. Sequence[str] isn't one of them: it's read by value, so two lists there now count per element too, as at top level (eeb73f9). A top-level Any or object field still reads [] as a value, so None vs [] is an FA there, and non_matches reads it the same way, also in a list element. Fixing that moves top-level scores, so I'll do it in the dispatcher and non_matches, tracked as a follow-up for 1.1.0. The classification docs and the CHANGELOG list it as a known difference.
Wrong class. ad608ac goes back to dev's rule. In an Any, object or Union[A, B] sub-field, two models of different classes are one TP or FD, from the GT model's compare_with() score against the field's threshold, with no subtree. Your Search vs Browse pair at threshold 0.9 is an FD again, and so is Inner(a, b="y") vs Other(c). The item's score for the field is still 1.0, because compare() skips the fields the prediction lacks. Fixing that stays with #327.
That rule still gives two TPs, both as on dev. compare_with() reads a field the prediction lacks as None, so an unset GT field matches it: Inner(a="x") vs Other(c="z") scores 0.5, from b, and is a TP at the default threshold of 0.5. It also scores only the GT's own fields, so Pet(tom) vs Cat(tom, 9) is a TP. The classification docs and the CHANGELOG name both, and f17b715 and ad608ac pin them.
An Optional union of models, or a union with a list arm, went through the dispatcher on dev and still does (95f16be). There Search vs Browse counts as at top level: a TP, with query 1 FN under aggregate.
| # score raised instead of scoring an FD (#400). | ||
| field_classification = gt_item._dispatch_field_comparison( | ||
| sub_field_name, gt_sub_value, pred_sub_value | ||
| )["overall"] |
There was a problem hiding this comment.
Medium: keeping only ['overall'] drops the fields subtree the dispatcher returns for model-valued sub-fields, so aggregate still differs from the top level.
For the wrong-class Union pair, aggregate for value is tp1 on the list path, but tp3 fn1 at the top level. Inner(a, b) vs Other(c) gives tp1 vs fn2. The is_simple_list branch at lines 516-537 already keeps the subtree with _recursive_aggregate_metrics. Using that loop for both branches made aggregate match the top level in every model-valued case, and the other 76 scenarios were unchanged.
There was a problem hiding this comment.
Done in 2c43b0e. Both branches now share the per-pair loop and _recursive_aggregate_metrics. So in an Any, object or Union[A, B] sub-field, a model of the GT's class keeps its fields under aggregate, as at top level: Inner(a="x", b="y") vs itself gives 2 TP, where dev gave 1. test_a_model_in_a_sub_field_keeps_its_leaves checks the list path and top level against the same literal counts.
Your two wrong-class pairs are the exception. They're back to dev's rule (thread 2), so each is one FD with no subtree, and their aggregate is 1 FD rather than top level's TP with FNs. The classification docs list this as a difference.
I also added a guard in 0999f7a. aggregate sums a node's children when it has any, so when one pair kept a model's fields, a pair holding None or a primitive dropped out. The node now keeps its subtree only when every pair has one. So [Inner(x), Inner(y)] vs [Inner(x), None] gives root aggregate 3 TP and 1 FN in an Any or object sub-field, and ["abc", Inner] vs itself gives 4 TP, both as on dev. test_a_sub_field_of_mixed_shapes_counts_every_pair pins them. A nested-model or list-annotated sub-field, such as Optional[Inner], still leaves such pairs out, as on dev: those pairs give that sub-field aggregate 1 TP and 1 TN, where top level gives 1 TP, 1 TN and 1 FN. The classification docs and the CHANGELOG say so (7b8841c), and fac2680 pins it for Optional[Inner], Inner | None, Annotated[Optional[Inner], Field(...)] and Optional[List[Inner]]. It is tracked as a follow-up for 1.1.0.
| with an explicit `LevenshteinComparator`) raised `TypeError` out of | ||
| `compare_with()` instead of warning and scoring an FD. Counts move for working | ||
| inputs too, though scores do not, and now agree with `non_matches`: | ||
| - a pair the comparator is not given at top level is an FD, not a TP the |
There was a problem hiding this comment.
Medium: the Breaking entry leaves out several count changes, so consumers who re-baseline from it will be surprised.
With value: Any, the entry covers only the both-empty pair. It omits:
(),set()orb''vsNone: TN becomes FN.Nonevs(): TN becomes FA.- null vs
[], and[]vs[](see line 553). - The model-valued
Any/Unionchanges: FD to TP and TP to FD, including wrong-class pairs.
The PR description says None and "" "count as before", which is false against [].
There was a problem hiding this comment.
I rewrote the entry around the rule rather than a list of inputs (e2d3287). A list element's sub-field is now classified by the same dispatcher as a top-level field, so its counts match top level, apart from four cases, and scores don't change. The list path skipped the dispatcher for any sub-field it didn't route as a nested model or a list: Any, object, Union[A, B], Dict and str, and also spellings such as Sequence[str], Sequence[Inner] and Optional[Annotated[Inner, Field(...)]]. Earlier versions tried to list every input that moves, and kept missing some, such as a Decimal or UUID against its string, two Enum classes, Inner against [Inner], or frozenset() against None. Their "count as before" sentence was also false for the Sequence and Annotated spellings, which now count as at top level. The bullets are now examples:
- a dict the comparator can't score raised
TypeError, and now warns and counts an FD; - a pair top level doesn't give the comparator is an FD, not a TP the score didn't credit: a tuple, a
DecimalorUUIDagainst its string, twoEnumclasses,Inner(a="x")against[Inner(a="x")]; - a value top level doesn't read as null, such as
(),frozenset(),b" "or" ", is no longer a TN against a null one; - two lists count per element, and a list of models keeps its fields, in
AnyorSequence[...]alike; - a model of the GT's class takes its verdict from the item's score for the field, so
Inner(a="hotel")vsInner(a="hotels")at 0.9 is an FD inAnyorOptional[Annotated[Inner, Field(...)]], as it already was inOptional[Inner]; - a union field two classes declare differently follows the first matched GT element that declares it, so with a
str-typed class first, a list-annotated field of another class now counts per element, as in the other order.
eeb73f9 and 9f85e15 pin the Sequence and Annotated rows, each against top level. The entry still names the AttributeError crash and its shapes, the object-level TP those pairs count, the fixed-score override rows (why most are TPs, and the shapes the dispatcher raises on, which keep dev's count: two lists, one FD from the comparator, cd3fb59, and two models of one class whose own compare_with() also returns a fixed score, such as Leaf(d=[Inner(a="x")]) against Leaf(d=[Point(x=1)]), one TP from that compare_with(), 823c451; a list-annotated sub-field such as List[Any] falls back the same way when the list's first element's class doesn't declare it as a list, efa47ca), the plain pydantic TypeError, and the ground-truth raise that remains, next to the one that was fixed. It lists the four cases that still differ from top level. Two apply to every sub-field. An extra field on the prediction, one its class doesn't declare, isn't counted, where top level counts an FA (5654027). A sub-field that mixes models with None across pairs keeps one shape under aggregate: one read by value keeps every pair as one leaf, and one that goes to the dispatcher directly, such as Optional[Inner], keeps the models' fields and leaves the None pair out, as on dev (7b8841c). fac2680 and 780c213 pin both. The other two apply to a sub-field not routed as a nested model or a list: a model of another class (with its TPs, Pet vs Cat and Inner(a="x") vs Other(c="z") at the default threshold), and an empty list read as null. The "Nested lists" note in classification-logic.md now says the same, and names by example which fields go to the dispatcher directly and which are read by value first (5814586). The entry also says that under a fixed-score element every sub-field now gets the dispatcher's warnings, as without the override, so a filterwarnings = error run raises there, where dev was silent (a5e8aa0, 9ab8ec9, pinned in f1aa451 and dfc5cc1). overall_score is unchanged in every row that ran on dev.
The entry is under Fixed now, not Breaking (1f0973d), and I've dropped the ! from the title. The project counts as breaking only an API change: a public name, parameter or result field, a default, input the docs accept that is now rejected, or a documented output format. This entry changes none of those. On input that ran on dev, every overall count it moves now matches top level and the item's own field score, with one exception: the empty-list rule the classification docs give for a sub-field read by value. Such a sub-field reads [] and [None] as null, so " ", (), set() or b"" against [] is an FN (the reverse an FA), where top level gives an FD. aggregate follows the documented mixed-shapes rule. Where the dispatcher can score them, the fixed-score override rows now count what the same pairs count without the override and at top level, which follows the field-by-field scoring StructuredModel still uses for objects of different classes, as the entry says. Where it raises, they keep dev's count. The one new raise is the dispatcher's warning under a fixed-score element, and only under warnings as errors. I've also updated the PR description. On the head you reviewed, it was wrong about None and "" against [], and its [] vs [] row and overlap section were stale.
| **List order** -- Order does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position. | ||
|
|
||
| **Nested lists** -- For `List[StructuredModel]`, the Hungarian algorithm pairs objects at the list level, then each matched pair is evaluated recursively. | ||
| **Nested lists** -- For `List[StructuredModel]`, the Hungarian algorithm pairs objects at the list level, then each matched pair is evaluated recursively. A field inside a list element is classified by the same rules as at top level. |
There was a problem hiding this comment.
Medium: "A field inside a list element is classified by the same rules as at top level" is false in three measured cases.
- A hallucinated extra field counts FA=1 at top level and nothing inside a list, because
_calculate_nested_field_metricsskipsextra_fields. - Mixed model classes raise inside a list (
structured_list_comparator.py:546). aggregatediffers for model-valued sub-fields (:555).
Fix those three cases, or narrow the sentence to the overall counts of declared fields.
There was a problem hiding this comment.
I fixed two in code and narrowed the sentence for the rest. Mixed classes no longer raise (2c43b0e, thread 1), and a model of the GT's class keeps its fields under aggregate (thread 3).
The "Nested lists" note now says every field the GT element's class declares follows the rules on the page. It then lists what a list element counts differently:
- an extra field, one the predicted element's class doesn't declare, isn't counted, where top level adds an FA to the root
overall; - a model of another class in
Any,objectorUnion[A, B]is one TP or FD fromcompare_with(). The note names the TPs this gives:PetvsCat, andInner(a="x", b=None)vsOther(c="z")at the default threshold; - a field that mixes models with
Noneor primitives across pairs keeps one shape underaggregate; - an empty list in an
Anyorobjectfield is null.
The different-classes warning also now says that pairing in a list of models uses compare(). So [Search] vs [Browse] pairs as a TP at score 0.0, and a model paired with a non-model element in an Any, object or List[Any] field is a TP the same way. It says these pairs, and one against a model of another class, count a TP also when the list element's class overrides compare_with() to return a fixed score. It also says a plain pydantic element raises TypeError against a model, and that under such an override a field read by value counts one TP or FD from its comparator wherever scoring the list would raise (f32912a).
A field that only the prediction's subclass declares isn't counted at top level either, so that case matches. Pet vs Cat gives 1 TP at the root, while Pet vs a Pet with an undeclared color gives 1 TP and 1 FA.
| def test_sub_field_counts_as_at_top_level(gt, pred): | ||
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore") | ||
| assert _in_list_counts(_in_list(gt, pred)) == _top_level(gt, pred) |
There was a problem hiding this comment.
Medium: the parity assertion compares two calls into the same dispatch_field_comparison, so it passes whatever the dispatcher returns.
On head, the list-path counts equalled the top-level counts in all 82 scenarios, including None vs [] (FA), [] vs [] (no count) and the wrong-class Union pair (TP). Pin expected counts for the empty-list and model-valued rows.
Separately, and lower priority: #398 and #399 have both merged, so StructuredModel._classify_field_for_confusion_matrix, ConfusionMatrixCalculator.classify_field_for_confusion_matrix, TestVerdictShape, and the stale module docstring in test_list_subfield_classification.py can be deleted in this PR, as its description planned.
There was a problem hiding this comment.
Agreed, it couldn't fail. 992fc09 pins literal counts in every row. Later commits add rows for other-class models, mixed shapes across pairs, a list against None, nested and list-annotated sub-fields whose counts don't move, Sequence[...] and Optional[Annotated[Inner, Field(...)]] sub-fields, which now count as at top level, object sub-fields, the fixed-score override rows (including the two-list shapes that keep dev's FD, two models of one class that keep dev's TP, list sub-fields the first element's class doesn't route as a list, and the dispatcher's warnings), a union field two classes declare differently, mixed shapes in a sub-field that goes to the dispatcher directly, an extra field on a predicted element, and the CHANGELOG's examples. None vs [] and [] vs [] are pinned at TN, as the classification docs say, and a whitespace string or empty tuple against a null value at FN. Inner(a, b) vs Other(c) and Search vs Browse in Any, object and Union[A, B] are pinned at FD, as on dev, and Inner(a="x") vs Other(c="z") at the default threshold at TP. Of the 238 tests, 113 fail on dev, 144 on the pre-fix merge e2377a5, and 144 on the pushed head 3145138. The 43 that pass on all three pin dev behaviour the docs now name. Since #398 and #399 are in, e30e6be also deletes the classifier (and with it confusion_matrix_calculator.py), its StructuredModel wrapper and TestVerdictShape, and it rewrites the stale module docstring. The deletion has no CHANGELOG entry, because all of it is private: the classifier and its wrapper are underscore methods, and the module is not exported. The earlier removals of uncalled private wrappers, three in #390 and one in #398, had none either. docs/structured_model_REFACTORING.md records it next to them. 15ffdc2 brings back only the classifier's list branch, as _comparator_result, for the one path that still needs it: two lists the dispatcher raises on, which only a fixed-score element reaches. ff33e1b likewise counts two models of one class the dispatcher raises on from the GT model's compare_with() (_compare_with_result), and b9ab522 extends both fallbacks to a list-annotated sub-field the list's first element's class doesn't route as a list. They are private too, and the CHANGELOG describes its effect, not the helper.
Resolve the CHANGELOG conflict: keep dev's 1.0.1 text and move this branch's entry into [Unreleased], since 1.0.1 has shipped.
…s null Review follow-ups on the list path in StructuredListComparator: - Read a pair's sub-field with getattr(..., None), as top level does, and classify each pair on its GT item's own fields. A list holding more than one model class (a subclass, or List[Union[A, B]]) raised AttributeError. - Keep the nested `fields` the dispatcher returns for a model held in an Any or Union sub-field, so `aggregate` matches top level. - Read an empty list as null by its value, as the classification docs say. The dispatcher does so only for a list-annotated field, so routing an Any sub-field through it turned None vs [] and [] vs [] from TN into FA, FN or no count. Two absent values are a TN again, and an absent list facing a non-list reads as None. Two lists still count per element.
…her calls The parity assertion compared two calls into the same dispatcher, so it passed whatever the dispatcher returned. Every row now expects literal counts, and new rows cover empty lists in an Any sub-field, a model's leaves in aggregate, and lists of mixed model classes.
ConfusionMatrixCalculator.classify_field_for_confusion_matrix and its StructuredModel wrapper lost their last caller when the list path moved to the dispatcher. Drop them, the test that only exercised the wrapper, and their mentions in the component maps.
Also keep the models README diff to the deleted file name.
…y claim The Breaking entry now comes from a before/after matrix against dev: empty tuples, sets, bytes and whitespace against None, per-element list counts, model-valued verdicts and aggregate including other-class pairs, and the two crashes. Scores do not change for any input that ran before. classification-logic.md no longer says a list element's field follows the top-level rules without exception: a field only the prediction has is not counted inside a list. The different-classes box now says a nested object is scored on the fields both objects have.
Two models of different classes in an `Any` or `Union` sub-field of a list element were classified through the dispatcher, which scores them with `compare()`. That skips the fields the prediction lacks, so `Inner(a, b)` vs `Other(c)` and `Search` vs `Browse` went from FD to TP. Classify such a pair as dev did: the GT model's `compare_with()` score against the field's threshold, one TP or FD, with no nested fields. A model of the GT's class still takes the item's score, as at top level. Fixing `compare()` itself stays with #327.
When one pair of an `Any` sub-field held a model, the merged node kept that model's fields, and `AggregateMetricsCalculator` summed only them. A pair with flat counts, such as a model against `None` or a string, dropped out of `aggregate` and the root. GT `[Inner(x), Inner(y)]` vs `[Inner(x), None]` gave root `aggregate` tp3 tn1 instead of dev's tp3 fn1. Keep the subtree only when every pair has one. A mixed node is one leaf again, as on dev, so it loses the model's leaves but counts every pair.
The override test passed through to `super().compare_with()`, so on dev it raised like the plain case and did not reproduce the reviewer's case. An override that returns a fixed score does: dev counts fd1, this branch tp1. The classification test's module docstring said only non-list sub-fields go through the dispatcher. `List[str]` and nested-model sub-fields do too, and a model of another class is classified by `compare_with()`.
…xtras line - classification-logic: drop the line saying two objects with no field in common score 1.0, since a list sub-field now counts them as dev did. The nested-lists note lists the two cases counted differently from top level: an undeclared extra field, and a model of another class in an `Any` or `Union` field. The extras line said "a field only the predicted element has", which is wrong for a subclass's own field. - CHANGELOG: name the cases that differ from top level instead of claiming parity and agreement with `non_matches`, widen the `AttributeError` bullet, and restrict "one per element" to two lists. - REFACTORING: count `_classify_field_for_confusion_matrix` among the removed methods, with its module.
… dispatcher ad608ac classified two models of different classes by `compare_with()` in every non-nested sub-field. Dev did that only for a field that is not list-annotated. A list-annotated one, such as `Union[Search, Browse, List[str]]` or `Union[Any, List[str]]`, took the simple-list branch, which sent every pair to the dispatcher. So `Search(query="hotels")` vs `Browse(url="x.com")` there moved from TP with `aggregate` fn1 to FD, and `Inner(a, b)` vs `Other(c)` lost its fn2 leaves. Read the annotation first and use `compare_with()` only when the field is not list-annotated. A test pins both rows and the `Optional[Union[...]]` case, which is routed as a nested model, at the counts top level gives.
2c43b0e read an empty list as null by its value in every sub-field. The rule exists because the dispatcher reads `[]` as null only in a list-annotated field. In a list-annotated field, such as `Optional[Union[str, List[str]]]` or `Union[Any, List[str]]`, it also turned `""`, `{}` and NaN into `None`, which the dispatcher there reads as values. Counts moved off dev and top level: `None` vs `""` went from FA to TN, and `""` vs `["a", "b"]` from 1 FA to 2. Apply both value-reading rules, empty values and other-class models, only to a sub-field that is neither nested nor list-annotated. Every other sub-field goes straight to the dispatcher, as on dev. A test pins the list-annotated rows at the counts top level gives.
…er pairs out Optional[Inner], Inner | None, Annotated[Optional[Inner], Field(...)] and Optional[List[Inner]] keep the model pair's fields under aggregate, so the None pair's FN drops out: 1 TP and 1 TN, where the same pairs at top level sum to 1 TP, 1 TN and 1 FN. Unchanged from dev.
An undeclared extra field on the prediction adds an FA to the root overall at top level, and nothing in a list element. Unchanged from dev.
Under an element compare_with() that returns a score without recursing, a sub-field holding a mapping or a plain pydantic model its comparator cannot score, or two plain models of different classes, now warns as it does without the override and at top level, and raises under warnings as errors. Dev was silent there. The score stays 1.0 and the pair is an FD.
The mixed-shapes case also holds where a sub-field goes to the dispatcher directly, such as Optional[Inner] or Optional[List[Inner]]: aggregate keeps the models' fields and leaves the other pairs out, as before. The scoping sentence now says the extra-field and mixed-shapes cases apply to every sub-field, and the bullet gives both shapes, as classification-logic.md does.
… prediction "A field the predicted element's class does not declare" also reads as a ground-truth field the prediction lacks, which is counted, as an FN. The case is an undeclared extra field on the prediction, which top level counts as an FA on the root overall.
Under an element compare_with() that does not recurse, the list path was the only reader of a sub-field and called its comparator silently. The dispatcher now warns there as it does without the override and at top level, which raises under warnings as errors.
…element The class-mismatch warning needs only one side to be a plain pydantic model: Point against Point2, Point against Inner and Inner against Point all warn. Two StructuredModels of different classes do not, since a field read by value scores them with compare_with().
warn_once on the pushed head recorded a warning before emitting it, so the raise under warnings as errors swallowed the later pytest.warns and the test failed there for a reason that is not the behaviour it pins. One call per test, with the conftest's per-test reset, checks each on every tree.
…e as dev did Under a list element whose compare_with() returns a score without recursing, a sub-field read by value (Any, object, Union[Leaf, Inner], Optional[Annotated[Leaf, Field(...)]]) can hold two models of one class whose own compare_with() also returns a fixed score, with fields the dispatcher raises on, such as Leaf(d=[Inner(a="x")]) against Leaf(d=[Point(x=1)]) (TypeError) or Leaf(d=[Inner(a="x"), "b"]) against itself (AttributeError). Dev scored these 1.0 and counted one TP from Leaf.compare_with(). The dispatcher recursed into Leaf and raised, with or without include_confusion_matrix, and one list level down plain compare() raised too. The fallback covered only two lists. When the dispatcher raises AttributeError or TypeError on two models of one class in a sub-field read by value, the pair now counts as on dev: one TP or FD from the ground-truth model's compare_with(). If that recurses, it raises as on dev. _other_class_result, which already scored two models of different classes that way, is renamed _compare_with_result. Every other input is unchanged.
…'s TP
Under an element compare_with() that returns a fixed score, a
FixedScoreLeaf pair whose Any field d holds [Inner] vs [Point], or
[Inner, "b"] against itself, scores 1.0 with field_scores
{"items": 1.0}, with and without include_confusion_matrix, and counts
value 1 TP, aggregate 1 TP, no fields. That holds in Any (two
thresholds), object, Union[FixedScoreLeaf, Inner] and
Optional[Annotated[FixedScoreLeaf, Field(...)]] sub-fields (20 rows),
one list level down under plain compare() and compare_with() (2), and
in the bulk evaluator, with no error and no FN (2). An
Optional[FixedScoreLeaf] sub-field, which goes to the dispatcher
directly, still raises, as on dev (2). The 24 non-control rows fail on
dfc5cc1; all 26 pass on dev.
…es on counts as before The CHANGELOG said that where the dispatcher raises under a fixed-score element, the pair counts one TP or FD from the comparator, and the classification docs said so "where scoring the list would raise". Both held only for a list directly in the field. They now say two lists count from the comparator and two models of one class from the ground truth's own compare_with(), which runs when that too returns a fixed score, with a Leaf example, and the CHANGELOG adds that a sub-field routed as a nested model or a list, such as Optional[Leaf] or List[Any], still raises on them, as before. The refactoring record names both fallbacks.
…oute as a list as dev did Dev read only the first ground-truth element's class, so a field that class lacks, or declares by value, never reached the dispatcher. HEAD reads every matched class, so such a field could reach it as a list with no fallback and raise where dev scored: - R-A: TaggedBase before a fixed-score subclass whose List[Any] or Optional[List[Any]] tags hold [Inner(a="x"), "b"] vs ["a", "b"] (AttributeError) or [Inner(a="x")] vs [Point(x=1)] (TypeError). Dev scored 1.0. Also one list level down and in the bulk evaluator. - R-B: List[Union[Note, Tags]] where Note declares v as Optional[str] or Any and fixed-score Tags as Optional[List[Any]]. When the Note pair failed its match verdict, Tags's annotation read v for every pair. Dev scored 0.667 (1.0 with a fixed-score Note). A pair whose sub-field the first element's class does not route as a nested model or a list now counts from the comparator, or from compare_with() for two models, when the dispatcher raises, as a pair read by value already did. When the first element's pair is not a match, each pair is read by its own class's annotation rather than the first matched one's. A field the first element's class routes as a list still raises, as on dev. On a 67,584-case grid of two classes per list, nothing raises that ran on dev or on 823c451, no score differs from dev, and no count differs from 823c451 where it ran. The R3 single-class grid output is byte-identical to 823c451's.
…ute as a list
R-A: TaggedBase listed before a fixed-score subclass with tags as
List[Any] or Optional[List[Any]], holding [Inner(a="x"), "b"] vs
["a", "b"] or [Inner(a="x")] vs [Point(x=1)]: score 1.0, field_scores
{"items": 1.0}, with and without include_confusion_matrix, and tags
1 FD, aggregate 1 FD, no fields (8). One list level down under plain
compare() and compare_with() (2), and in the bulk evaluator with no
error (2). With the subclass first, it still raises, as on dev (4).
R-B: [Note, FixedScoreTags] in a union whose Note declares v as
Optional[str], Any, or Optional[str] with a fixed-score compare_with(),
the Note pair failing: score 2/3, 2/3 and 1.0, v 1 FD, with and
without the confusion matrix (12), and in the bulk evaluator (2).
A later AnyNote pair after a failed first pair is read by value, so
"x" against [] is an FN, as with the first pair matched (2).
All 32 pass on HEAD. On 823c451, 27 fail: every row but the 4
still-raises controls and the first-matches row. On dev 6f76236, 10
fail, all on counts dev did not take: tags in R-A (dev skipped it) and
the Tags pair's lists, which dev counted as one TP.
…ute so counts as before The CHANGELOG said a sub-field routed as a nested model or a list still raises, as before, under a fixed-score element. That now holds only when the list's first element's class routes it that way too. It now says so, and that otherwise the pair counts the same way: a fixed-score subclass's List[Any] field after its base counts one FD for [Inner(a="x"), "b"] vs ["a", "b"], where dev did not count it, and a union class's Optional[List[Any]] field counts one FD, as on dev, when the first element's class declares it Optional[str] or Any. The union bullet, classification-logic.md and the refactoring record add that a failed first pair leaves each pair read by its own class.
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
Measured at head efa47ca against origin/dev c70ca6e, with PYTHONPATH pointed at each tree's src. All 15 CI checks pass.
Suite
| Tree | Main suite | test_docs_build + test_readme_examples |
ruff check |
|---|---|---|---|
Head efa47ca |
4711 passed, 13 skipped, 1 xfailed | 88 passed | clean |
Head merged into origin/dev (no conflicts) |
4711 passed, 13 skipped, 1 xfailed | 88 passed | clean |
The 13 skips are the bert/strands extras and two placeholder tests. None is on the list comparator path.
My six findings from the 2026-10-30 review, all resolved
- A list holding more than one model class raised
AttributeError: fixed._dispatch_pairsreads the prediction withgetattr(..., None)(L408-L412).pets: List[Pet]with[Cat(tom, 9), Pet(rex)]against itself: dev raises'Pet' object has no attribute 'lives'. Head scores 1.0. A perfectList[Union[Search, Browse]]prediction also no longer raises. - Empty lists in an
Anysub-field: fixed.Nonevs[]and[]vs[]are each 1 TN, as on dev."x"vs[]is 1 FN. The top level still reads[]as a value, and the PR documents that difference for 1.1.0. - A wrong-class model in a
Unionsub-field moved from FD to TP: fixed by returning to dev's rule (L414-L417).SearchvsBrowseat threshold 0.9 is an FD on head and on dev. aggregatedropped thefieldssubtree: fixed for models of the same class.Inner(x, y)vs itself now givesaggregate2 TP, the same as the top level (dev gave 1). The guard at L658-L663 keeps a subtree only when every pair has one, so[Inner(x), Inner(y)]vs[Inner(x), None]still gives 3 TP and 1 FN.- CHANGELOG and
classification-logic.mdunder-stated the count changes: fixed. All 29 checked rows of the PR body's table reproduce, and so do the CHANGELOG and docs examples. A sweep of 2,888Any/objectvalue pairs plus 365 pairs across 9 other annotations found only the documented differences from top level: an empty list read as null, or a model of another class. No score moved between dev and head. - The parity test could not fail: fixed. Every row asserts literal counts. The test file fails with 113 failures on dev and 144 on
3145138. Of 22 mutations, the tests caught 17. The 5 survivors are listed below; 3 are behaviourally near-equivalent.
Also checked and cleared
- Issue #400's repro: dev raises
TypeError. Head scores 0.5, counts 1 FD and warns.Closes #400is correct. - No stale references to the deleted classifier or module remain in the merged tree.
BulkStructuredModelEvaluatorand the printed confusion matrix work with the new field nodes.- The
except (AttributeError, TypeError)fallback calls the same comparator again, so a real error is raised again rather than hidden. - Speed: a 150-item list takes 0.723 s on head and 0.724 s on dev.
- Moving the entry from Breaking to Fixed and dropping the
!reverses my earlier comment. The current[Unreleased]section files score changes under Fixed (#506, #559), so I leave this to the maintainers.
Non-blocking (low)
- L330-L335: the rule "the first matched ground-truth element's class decides" has no test when the list-annotated class comes first.
[BList(x=["a"]), AAny(x=None)]vs[BList(x=["a"]), AAny(x=[])]countsxas 1 TP, 1 FA. Withreader = Noneit counts 1 TP, 1 TN, and the full suite still passes. - Same lines: one pair's count depends on another pair. The same
AAnypair (Nonevs[]) counts FA when element 0 matches and TN when it does not. This is documented and narrow. [Cat(tom, 9), Pet(rex)]vs[Pet(rex)]produces alivesnode with all counts zero; the reverse order produces none. Dev raised here. The empty node is harmless.- Untested mutations: forcing
is_simple_listto False, and removingNullHelper.present()from_comparator_result(no test feeds a fallback list holdingNone).
|
verdict: the crash fix works, but this PR should be split before it goes into 1.0.2. measured on
minimum for 1.0.2: a crash-only PR that sends the unscorable dict in an one question: will you split it that way, or keep #406 whole and move #400 to 1.1.0? |
Keep #406's Nested lists rules with the list contract's TP-pair wording (an FD pair is not descended into, measured on the merged tree), and point the Known gaps note at those cases: the value kinds it listed now count as at top level.
|
Thanks Diego, and sorry this merged before I answered. You're right that my 3 Nov scope said crash-only. I've since proposed a definition of breaking in #587: counts that move to match the documented top-level rules, with no score change, count as a fix rather than a contract change. On that basis, I kept #406 whole. vawsgit's run and our 521,950-case grid both showed no On the deleted |
awslabs#406 removed ConfusionMatrixCalculator while this branch removed ConfusionMatrixBuilder, so the metrics lists in the refactoring notes and the models README now name neither. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
awslabs#406 deleted the module. It was never exported or documented, but its import path worked, so restore it unchanged for 1.0.x with a DeprecationWarning on import. Nothing in Stickler imports it; removal moves to 1.1.0.
Closes #400.
What was wrong
For each matched pair in a
List[StructuredModel],StructuredListComparator._handle_non_hierarchical_fieldcounted a sub-field it did not route as a nested model or a list (Any,object,Union[A, B],Dict,str, and spellings such asSequence[str],Sequence[Inner]orOptional[Annotated[Inner, Field(...)]]) with_classify_field_for_confusion_matrix, which calls the field's comparator directly. That skipped the dispatcher's guards, so the list path had its own verdict, different from top level and from the item's own score. Sub-fields annotated as a model, a list, or anOptionalmodel or union of models already went through the dispatcher. Two kinds of input crashed:TypeErrorout ofcompare_with(), with or withoutinclude_confusion_matrix. This happened in anAnyorUnion[A, B]sub-field, or in aDictone with an explicitLevenshteinComparator.AttributeErrorat a baregetattr. That covers a subclass listed before its base, andList[Union[A, B]]. It also covers a list of models in anAny,objectorList[Any]field, at top level or inside a list element, against a list holding a dict, string, number, list or model of another class.The change
_dispatch_pairs, which reads both values withgetattr(..., None)and calls the GT item's_dispatch_field_comparison. Each pair is classified on its own GT element's declared fields.StructuredModelis left out of field classification, since it has no dispatcher.Optionalmodel or union of models goes straight to the dispatcher, as on dev. A field's kind comes from the first matched GT element whose class declares it, so in a union whose classes declare one field differently, that element's class decides (see "Lists of models"). When the list's first element is not matched, each pair's own class decides.Sequence[...]andOptional[Annotated[Inner, Field(...)]], is read by value first. This keeps two dev rules the dispatcher does not have:classification-logic.mdsays, soNonevs[]and[]vs[]stay TN. The dispatcher reads[]as null only in a list-annotated field;compare_with()score against the field's threshold: one TP or FD, with no subtree. The dispatcher'scompare()skips the fields the prediction lacks and would scoreSearchvsBrowse1.0. Fixing that stays with A different class, including a subclass, should always be a false discovery #327.aggregatewhen every pair has them. Otherwise every pair stays one leaf, as on dev, so a pair holdingNoneor a primitive still counts.AttributeErrororTypeErroron two lists, the pair is counted from the field's comparator, as on dev (_comparator_result). The dispatcher raises on a list of models against plain pydantic models, or with a matched GT value that has nocompare_with(). Scoring the element walks the same field first and raises the same way, so only an element whosecompare_with()does not recurse gets here. Such inputs scored 1.0 on dev and still do.compare_with(), as on dev (_compare_with_result).List[Any], that the list's first element's class does not declare that way, since dev read only that class's fields. A fixed-score subclass'sList[Any]field listed after its base counts 1 FD for[Inner(a="x"), "b"]against["a", "b"], where dev did not count it. When the list's first element is not matched, each pair is read by its own class's annotation. Anything else re-raises._classify_field_for_confusion_matrix, its moduleconfusion_matrix_calculator.py, andTestVerdictShapeare deleted. Nothing calls them now that refactor(395): remove the remaining dead confusion-matrix paths #398 and fix!: treat a None list element as absent (#386, #322) #399 are in.Release
A fix for 1.0.2, under
[Unreleased]> Fixed, with no**Breaking:**label and no!. Breaking here means an API change: a public name, parameter or result field removed, renamed or retyped, a default changed, input the docs accept now rejected, or a documented output format changed. This PR does none of these. The deletedConfusionMatrixCalculatoris named only as an internal helper, in theStructuredModeldocstring's helper list next toComparisonEngine. It is not exported, no user doc mentions it, and the architecture guide says internal helpers are not public API._classify_field_for_confusion_matrixis private.The rule: a list element's sub-field is classified by the same dispatcher as a top-level field, so its counts match top level, apart from four documented cases, and no score moves. On input that ran on dev, each moved
overallcount now matches what the same input counts at top level and the item's own field score against its threshold, with one documented exception. In a sub-field read by value, such asAnyorobject, the list path reads[]and[None]as null, asclassification-logic.mdsays. So a value such as" ",(),set()orb""against[]is an FN (the reverse an FA), where top level reads[]as a value and gives an FD.aggregatefollows the documented mixed-shapes rule. The other moved rows are inputs that raised on dev. Under an elementcompare_with()that does not recurse, a sub-field now also gets the dispatcher's warnings, as without the override (see "Behaviour changes"). That raises only under warnings as errors.The fixed-score override rows move too. When a list element's class overrides
compare_with()to return a score without recursing, a list of models in itsAnyorobjectsub-field ran on dev against a list of non-models or of models of another class. It counted one FD, except a model of another class at the default threshold, which was already a TP.[Inner(a="x")]against["a"],[1],[["a"]]or[{"a": "x"}]is now a TP, at score 1.0 on both, and so is[Inner(a="x")]against[Other(c="z")]at a field threshold of 0.9. That is what the pair counts without the override and at top level, and how the different-classes warning describes these pairs. For a non-model element it goes against that section's headline, that objects of different classes are always an FD, which is not yet applied toStructuredModel. It stays a TP untilStructuredModelfollows the different-classes rule (#327). Where the dispatcher raises, as it does at top level and without the override, the pair keeps dev's count, from the comparator:[Inner(a="x")]against[Point(x=1)], or[Inner(a="x"), "b"]against["a", "b"], is 1 FD at score 1.0 on both. It changes no name, default, accepted input or format, so it is not breaking.Behaviour changes
Counts on
items.fields.value, measured on dev8c56dfa6and on this branch. The sub-field isvalue: Anywith an inferred comparator unless noted.overall_scoreis the same on both in every row that ran on dev. The rows are examples of the rule, not a complete list: in a sub-field read by value, any count that differed from top level now matches it, apart from the four cases below.{"text": "p"}{"text": "q"}TypeError("a", "b")("a", "b"){"a"}{"a"}b"ab"b"ab"date(2020, 1, 1)"2020-01-01"Decimal("1.5")"1.5"UUID(int=1)A.xB.x, twoEnumclasses with value"x"Inner(a="x")[Inner(a="x")]Point(x=1)(plain pydantic)Point(x=2){"a": "x", "b": "y"},Dict[str, str]withFuzzyComparator{"a": "x", "b": "z"}()()()NoneNone()frozenset(),bytearray(b"")orb" "None" ""x"" "" "" "None" """" "[][]()["a", "b"]["a", "c"]["a", "b"]["b", "a"]["a", "b"][][]["a", "b"]["a", "b"],Sequence[str]["a", "c"]["a", "b"],Sequence[str][][Inner(a="x", b="y"), Inner(a="p", b="q")],Sequence[Inner]aggregate1 TPaggregate4 TPInner(a="hotel"),valuethreshold 0.9Inner(a="hotels")Inner(a="hotel"),Optional[Annotated[Inner, Field(...)]], threshold 0.9Inner(a="hotels")aggregate1 TPaggregate1 TP, 1 TN, as inOptional[Inner]Clip(a="hotel"),athreshold 0.9 and clipped,valuethreshold 0.8Clip(a="hotels")Inner(a="x", b="y")aggregate1 TPaggregate2 TP[Inner(a="x")][{"a": "x"}]AttributeErroraggregate1 FN, 1 TN[Inner(a="x")], elementcompare_with()returns a fixed score,Anyorobject["a"],[1],[["a"]]or[{"a": "x"}]aggregate1 FN, 1 TN (see Release)valuethreshold 0.9[Other(c="z")]aggregate1 FN, 1 TN[Other(c="z")]aggregate1 TPaggregate1 FN, 1 TNFor a model of the GT's class, the verdict now comes from the item's score for the field, as at top level, so it can move either way. The
" "and()rows against a null value hold forset()andb""too, againstNone,"",{}, NaN,[]or[None], and in anobjectsub-field." "vs""moves the same way in astrorOptional[str]sub-field. AgainstNone,"",{}and NaN these now match top level. Against[]and[None]they are the documented exception above.Lists of models:
[Cat(tom, 9), Pet(rex)]vs itself, and aList[Union[Search, Browse]], raisedAttributeErroron dev. Both now score 1.0, andlivesis counted for the Cat pair only.[Pet(rex), Cat(tom, 9)]vs[Pet(rex), Pet(tom)]ran on dev withname2 TP. It now also countslives1 FN. The score is 0.75 on both.[Search(query="hotels")]vs[Browse(url="x.com")]inList[Union[Search, Browse]], or in anAnyfield, raised on dev. It now counts an object-level TP withquery1 FN underaggregate, while the field scores 0.0. A model against a non-model element, such as[Inner(a="x")]vs["a"], is a TP the same way. The pairing verdict comes fromcompare(), which skips the fields the prediction lacks (A different class, including a subclass, should always be a false discovery #327). The CHANGELOG and the different-classes warning inclassification-logic.mdsay so.[Inner(a="x")]vs[Other(c="z")]in anAnyorobjectfield, and[Inner(a="x")]vs["a"]in aList[Any]one, also raised on dev, and are TPs the same way. The CHANGELOG names both.[Inner(a="x"), Scored()]vs itself in anAnyfield, at top level or in a list element, raisedAttributeErroron dev and on the pushed head3145138.Scoredis a plain pydantic model whosecompare_with()returns{"overall_score": 1.0}. It now scores 1.0, withvalue2 TP andaggregate1 TP, 1 TN. Its pair's verdict comes from the pairing, not from thatcompare_with(), so with one that returns 0.0 the list counts 2 TP at score 0.5. That is tracked as a follow-up for 1.1.0. The CHANGELOG names this fix, and the ground-truth case that still raises (below).List[Union[AStr, BList]], whereAStr.xisOptional[str]andBList.xisOptional[List[str]],xfollows the first matched GT element that declares it. WithAStrfirst,[AStr(x="p"), BList(x=["a", "b"])]vs[AStr(x="p"), BList(x=["a", "c"])]countedx2 TP on dev, and now counts 2 TP and 1 FD, as both trees count withBListfirst. WithBNested.x: Optional[Inner]in place ofBList,Inner(a="x")vsInner(a="y")moves from TP to FD the same way:xgoes from 2 TP to 1 TP and 1 FD, and rootaggregatefrom 4 TP to 3 TP and 1 FD. The scores (0.875 and 0.75) do not move.Warnings under a fixed-score element. Such an element never scores its fields, so on dev the list path was the only reader of a sub-field, and it called the comparator without the dispatcher's warnings. On this branch the dispatcher warns there, as it does without the override and at top level. Dev already warned for an element that recurses. With default filters the score is 1.0 on both, and the count moves by the rule above:
valueDict[str, str]withFuzzyComparator{"text": "p"}vs itselfAnyPoint(x=1)vs itselfAnyPoint(x=1)vsInner(a="x")Under warnings as errors, such as pytest's
filterwarnings = error, these inputs raiseUserWarningon this branch only. The CHANGELOG says so. TwoStructuredModels of different classes do not warn on either tree.Unchanged from dev, and pinned in tests:
Nonevs[],[]vsNoneand[]vs[]are TN,"x"vs[]is FN, and["a", "b"]vsNoneis 1 FN;Any,objectorUnion[A, B], at the field's threshold of 0.9:Inner(a, b="y")vsOther(c)andSearchvsBrowseare FD, andPet(tom)vsCat(tom, 9)is TP, sincecompare_with()scores only the GT's own fields. At the default threshold of 0.5,Inner(a="x")vsOther(c="z")is a TP too:compare_with()reads thebthatOtherlacks asNone, which matches the unsetb, so the pair scores 0.5. The CHANGELOG andclassification-logic.mdsay so;Optional[Union[Search, Browse]]orUnion[Search, Browse, List[str]],SearchvsBrowseis TP withaggregate1 FN. InUnion[Any, List[str]],Inner(a, b)vsOther(c)is TP withaggregate2 FN;Optional[Union[str, List[str]]]:Nonevs""is FA,""vs["a", "b"]is 1 FA, and["a", "b"]vs""is 1 FN, as at top level;Anyorobjectsub-field that mixes a model withNoneor a primitive across pairs: rootaggregateis 3 TP, 1 FN for[Inner(x), Inner(y)]vs[Inner(x), None], and 4 TP for["abc", Inner]vs itself;AttributeErrorwhen a matched ground-truth element has nocompare_with(), such as[Inner(a="x"), "b"]against itself in anAnyfield, at top level or in a list element.[Inner(a="x"), 1]and[Inner(a="x"), {"a": "x"}]raise the same way. Scoring the list as a list of models calls each matched GT item'scompare_with().["b", Inner(a="x")]against itself runs, and so does[Inner(a="x"), "b"]against[Inner(a="x")], where the string is unmatched. At top level both trees count them as 2 TP, and as 1 TP and 1 FN. In a list element'sAnysub-field dev counted each as 1 TP, and this branch counts per element, as at top level. This raise is not fixed, and the CHANGELOG says so;compare_with()that returns a fixed score, in anAnyorobjectsub-field:[Inner(a="x"), v]against["a", "b"], forva string, number, dict, list orPoint(x=1), and[Inner(a="x")]against[Point(x=1)]or[Point(x=1), Point(x=2)], are 1 FD at score 1.0, with no fields. The pushed head3145138raised on all of them. A model against a plain pydantic element without the override still raisesTypeError, at top level too, and the CHANGELOG says so.I also compared dev and this branch on every valid pair from 17 values in
Union[Any, List[str]]andOptional[Union[str, List[str]]]. I did the same with 4 to 6 values in four nested-model sub-fields and anOptional[List[str]]one, the last five also as two-pair lists. Every count andaggregatematches dev. Spellings read by value, such asSequence[...]andOptional[Annotated[Inner, Field(...)]], are not in that set: their counts move to top level's (above).The list path still differs from top level in four cases. The extra-field and mixed-shapes cases apply to every sub-field, and the other two to a sub-field read by value, such as
Any,object,Union[A, B]orSequence[str]. All four are named in the CHANGELOG and inclassification-logic.md, and each is pinned:overall. A field the GT's class declares and the prediction lacks is counted, as an FN;Noneor a primitive,aggregatekeeps one shape. In a sub-field read by value, each pair is one leaf, and a model of another class has the same effect:[Inner(x), Inner(y)]vs[Inner(x), None]givesvalue.aggregate1 TP, 1 FN. In a sub-field that goes to the dispatcher directly, the models' fields are kept and the other pairs are left out, as on dev: inOptional[Inner],Inner | None,Annotated[Optional[Inner], Field(...)]orOptional[List[Inner]], the same pairs give 1 TP, 1 TN. The same pairs at top level give 1 TP, 1 TN, 1 FN. The second shape is tracked as a follow-up for 1.1.0;AnyoneNonevs[]is TN and"x"vs[]is FN. Top level andnon_matchesgive FA and FD. The top-level andnon_matchesside is tracked as a follow-up for 1.1.0.Docs
CHANGELOG.md,[Unreleased]> Fixed: the rule (a list element's sub-field is classified by the same dispatcher as a top-level field, so its counts match top level, apart from four cases; scores do not change), with representative examples rather than a complete list, naming theSequenceandOptional[Annotated[...]]spellings. It also covers both crashes, including theobject,List[Any]and other-class shapes, the ground-truth-side crash that remains and the one fixed for a self-scoring non-model element, the object-level TP an other-class or non-model pair now counts, the fixed-score override rows, including the shapes the dispatcher raises on, which keep dev's count (two lists from the comparator, and two models of one class from their owncompare_with(), also in a list-annotated sub-field the list's first element's class does not route as a list), the plain pydanticTypeError, the dispatcher's warnings a fixed-score element's sub-fields now get, the union field that follows the first matched GT element declaring it, the empty values against null ones, and the four cases: the extra-field and mixed-shapes cases for every sub-field, and the other-class and empty-list cases for a sub-field read by value.docs/docs/Advanced/classification-logic.md, "Nested lists": every field a pair's GT class declares goes through the same dispatcher as at top level and follows the page's rules. It names by example the fields that go to the dispatcher directly and the ones read by value first, and says the first matched GT element that declares a field decides when classes annotate it differently, or each pair's own class when the list's first element is not matched. It lists the cases a list element counts differently: extra fields, and in a field read by value, a model of another class (includingPetvsCat, andInner(a="x", b=None)vsOther(c="z")at the default threshold, as TPs), mixed shapes underaggregate, and an empty list. The "Objects of different classes" warning also names the list pairing TP in anAny,objectorList[Any]field:[Search]vs[Browse], and a model paired with a non-model element. It says these pairs, and one against a model of another class, count a TP also under a fixed-score elementcompare_with(). It excepts a plain pydantic element, which raisesTypeError, and says that under a fixed-score element, in a field read by value, where scoring two lists would raise the field counts one TP or FD from its comparator, and where scoring two models of one class would raise it counts one from the ground-truth model's owncompare_with(). A field that goes to the dispatcher directly, such asList[Any], counts the same way when the list's first element's class does not declare it as a model or a list.docs/structured_model_REFACTORING.md: the deleted classifier and module, which sub-fields_dispatch_pairsreads by value, the two fallbacks,_comparator_resultand_compare_with_result, and when a directly routed sub-field may fall back (may_fall_back).src/stickler/structured_object_evaluator/models/README.md: dropsconfusion_matrix_calculator.pyfrom the Metrics list.Tests
tests/structured_object_evaluator/test_list_item_subfield_parity.pyhas 238 tests, each pinning literal counts, a raise or a warning. 113 fail on the merged dev6f762364, 144 on the pre-fix mergee2377a5, and 144 on the pushed head3145138. They pin, among others: a base-first list counts the subclass's fields; aSearchvsBrowsepair is a TP at score 0.0; a list of models in anAny,object,List[Any]orUnion[Any, List[str]]field (or anAnysub-field) against non-models or a model of another class no longer raises; under an elementcompare_with()that returns a fixed score, such a list in anAnyorobjectsub-field is a TP at score 1.0, withaan FN andba TN underaggregate, except against plain pydantic models or with a GT value that has nocompare_with(), which are 1 FD as on dev, and two models of one class whose own fixed-scorecompare_with()the dispatcher cannot recurse past, which are 1 TP as on dev; a fixed-score subclass'sList[Any]field after its base, and a union class'sOptional[List[Any]]field after astr-typed first element, run as on dev, also in the bulk evaluator and with a non-matching first element; under such an element, a sub-field the dispatcher warns about warns, and raises under warnings as errors; a union field two classes declare differently counts per element with either class first; aSequence[str]orSequence[Inner]sub-field counts per element, with a list of models' fields, and anOptional[Annotated[Inner, Field(...)]]one counts asOptional[Inner]does, both as at top level; a ground-truth list holding a self-scoring non-model runs; and a whitespace string or empty tuple against a null value is an FN, in a list element as at top level. 43 pass on all three, because they pin dev behaviour the docs now name, among them a subclass-first list that still raises: the list-annotated and nested sub-fields whose counts do not move, including theOptional[Inner]control next to theAnnotatedrow, the union field with its list-annotated class first,PetvsCatandInner(a="x")vsOther(c="z")as TPs, mixed shapes underaggregate, in a sub-field read by value and in one that goes to the dispatcher directly, an extra field on a predicted element, three primitive rows, and the ground-truth raise and the two ground-truth lists that run at top level.test_list_subfield_classification.pykeeps its 4 model-valued rows.Full suite
Python 3.12.6, with
inspect.getfile(stickler)in this branch'ssrc.ruff check .is clean.pytest -q --ignore=tests/test_docs_build.py: 4711 passed, 13 skipped, 1 xfailed.pytest -q tests/test_docs_build.py tests/test_readme_examples.py: 88 passed.