Repository navigation
fix(400): classify a list element's sub-field through the top-level dispatcher #406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
b74079d
e7810fa
89fd840
3145138
e2377a5
2c43b0e
992fc09
e30e6be
2452289
8252c77
ad608ac
0999f7a
a9a9542
b26a6b5
95f16be
0a52737
01b2c9f
9a4b615
b643ce2
1f0973d
f755ea4
f98703e
2df3183
f17b715
b756a79
e069405
f9f0fc3
e40c334
e414a7c
bfea4ad
9ae4385
1269607
776449e
eee3e1b
e34e9b8
5dc6c0e
0100113
3446fe5
ce4a97d
f39c15f
eeb73f9
9f85e15
e2d3287
5814586
15ffdc2
57d5c1c
cd3fb59
f32912a
b0890cc
fac2680
780c213
f1aa451
7b8841c
5654027
a5e8aa0
9ab8ec9
dfc5cc1
ff33e1b
5746007
823c451
b9ab522
c8e5d72
efa47ca
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
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.
- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -510,8 +510,8 @@ def _handle_non_hierarchical_field( | |
|
|
||
| # Classify through the dispatcher, as the branches above do, so | ||
| # a sub-field counts the way it does outside a list. Calling the | ||
| # comparator directly skipped its guards, so a dict in an `Any` | ||
| # sub-field raised instead of scoring an FD (#400). | ||
| # 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( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Blocker: routing through the dispatcher changes empty-list counts, and wrong-class predictions now count as TP. Empty lists. For
This contradicts Wrong-class predictions. A StructuredModel in an
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed on both, thanks. Empty lists. In a sub-field the list path reads by value, such as Wrong class. ad608ac goes back to dev's rule. In an That rule still gives two TPs, both as on dev. An |
||
| sub_field_name, gt_sub_value, pred_sub_value | ||
| )["overall"] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: keeping only For the wrong-class
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done in 2c43b0e. Both branches now share the per-pair loop and 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 I also added a guard in 0999f7a. |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,10 +4,12 @@ | |
| counted a primitive sub-field by calling the field's comparator directly, not | ||
| through `_dispatch_field_comparison`. That skipped the dispatcher's guards, so: | ||
|
|
||
| - a dict in an `Any` sub-field raised `TypeError` out of `compare_with()`, where | ||
| the same field at top level warns and scores an FD; | ||
| - a tuple, a set, or a `date` against its ISO string counted a TP that the | ||
| item's score did not credit; | ||
| - a dict the field's comparator cannot score raised `TypeError` out of | ||
| `compare_with()`, where the same field at top level warns and scores an FD; | ||
| - a pair the comparator is not given at top level (with an inferred | ||
| comparator, a tuple, a set, `bytes`, or a `date` against its ISO string; a | ||
| plain pydantic model under `LevenshteinComparator`) counted a TP that the | ||
| item's score did not credit, and that `non_matches` reported as an FD; | ||
| - a list in an `Any` sub-field counted one unit instead of one per element; | ||
| - a whitespace-only string counted as null. | ||
|
|
||
|
|
@@ -17,11 +19,17 @@ | |
|
|
||
| import datetime | ||
| import warnings | ||
| from typing import Any, List | ||
| from typing import Any, Dict, List | ||
|
|
||
| import pytest | ||
| from pydantic import BaseModel | ||
|
|
||
| from stickler import ComparableField, StructuredModel | ||
| from stickler import ( | ||
| ComparableField, | ||
| LevenshteinComparator, | ||
| NonMatchType, | ||
| StructuredModel, | ||
| ) | ||
|
|
||
| COUNTS = ("tp", "fa", "fd", "fp", "tn", "fn") | ||
|
|
||
|
|
@@ -40,6 +48,20 @@ class Flat(StructuredModel): | |
| value: Any = ComparableField() | ||
|
|
||
|
|
||
| class MappingElement(StructuredModel): | ||
| key: str = ComparableField(threshold=1.0) | ||
| value: Dict[str, str] = ComparableField(comparator=LevenshteinComparator()) | ||
| match_threshold = 0.4 | ||
|
|
||
|
|
||
| class MappingHolder(StructuredModel): | ||
| items: List[MappingElement] = ComparableField() | ||
|
|
||
|
|
||
| class Point(BaseModel): | ||
| x: int | ||
|
|
||
|
|
||
| def _counts(node): | ||
| return {k: node["overall"][k] for k in COUNTS} | ||
|
|
||
|
|
@@ -51,10 +73,15 @@ def _top_level(gt, pred): | |
| return _counts(result["confusion_matrix"]["fields"]["value"]) | ||
|
|
||
|
|
||
| def _in_list(gt, pred): | ||
| result = Holder(items=[Element(key="k", value=gt)]).compare_with( | ||
| Holder(items=[Element(key="k", value=pred)]), include_confusion_matrix=True | ||
| def _in_list(gt, pred, **kwargs): | ||
| return Holder(items=[Element(key="k", value=gt)]).compare_with( | ||
| Holder(items=[Element(key="k", value=pred)]), | ||
| include_confusion_matrix=True, | ||
| **kwargs, | ||
| ) | ||
|
|
||
|
|
||
| def _in_list_counts(result): | ||
| items = result["confusion_matrix"]["fields"]["items"] | ||
| return _counts(items["fields"]["value"]) | ||
|
|
||
|
|
@@ -66,24 +93,60 @@ def _in_list(gt, pred): | |
| pytest.param({"text": "p"}, {"text": "p"}, id="identical-dict"), | ||
| pytest.param(("a", "b"), ("a", "c"), id="tuple"), | ||
| pytest.param({"a"}, {"b"}, id="set"), | ||
| pytest.param(b"ab", b"ab", id="bytes"), | ||
| pytest.param(Point(x=1), Point(x=2), id="plain-model"), | ||
| pytest.param(datetime.date(2020, 1, 1), "2020-01-01", id="date-vs-str"), | ||
| pytest.param(["a", "b"], ["a", "c"], id="list"), | ||
| pytest.param(["a", "b"], ["b", "a"], id="reordered-list"), | ||
| pytest.param(" ", "x", id="whitespace"), | ||
| pytest.param(" ", None, id="whitespace-vs-none"), | ||
| pytest.param("abc", "abd", id="str"), | ||
| pytest.param(None, "x", id="none-vs-str"), | ||
| ], | ||
| ) | ||
| def test_sub_field_counts_as_at_top_level(gt, pred): | ||
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore") | ||
| assert _in_list(gt, pred) == _top_level(gt, pred) | ||
| assert _in_list_counts(_in_list(gt, pred)) == _top_level(gt, pred) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: the parity assertion compares two calls into the same On head, the list-path counts equalled the top-level counts in all 82 scenarios, including Separately, and lower priority: #398 and #399 have both merged, so
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 |
||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "gt, pred, expected", | ||
| [ | ||
| pytest.param(("a", "b"), ("a", "b"), NonMatchType.FALSE_DISCOVERY, id="tuple"), | ||
| pytest.param(" ", "x", NonMatchType.FALSE_DISCOVERY, id="whitespace"), | ||
| pytest.param(" ", None, NonMatchType.FALSE_NEGATIVE, id="whitespace-vs-none"), | ||
| ], | ||
| ) | ||
| def test_sub_field_counts_agree_with_non_matches(gt, pred, expected): | ||
| result = _in_list(gt, pred, document_non_matches=True) | ||
|
|
||
| reported = [ | ||
| n["non_match_type"] | ||
| for n in result["non_matches"] | ||
| if n["field_path"] == "items[0].value" | ||
| ] | ||
| assert reported == [expected] | ||
| count = { | ||
| NonMatchType.FALSE_DISCOVERY: "fd", | ||
| NonMatchType.FALSE_NEGATIVE: "fn", | ||
| }[expected] | ||
| assert _in_list_counts(result)[count] == 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("include_confusion_matrix", [False, True]) | ||
| def test_dict_in_any_sub_field_warns_instead_of_raising(include_confusion_matrix): | ||
| gt = Holder(items=[Element(key="k", value={"text": "p"})]) | ||
| pred = Holder(items=[Element(key="k", value={"text": "q"})]) | ||
| @pytest.mark.parametrize( | ||
| "holder, element", | ||
| [ | ||
| pytest.param(Holder, Element, id="any"), | ||
| pytest.param(MappingHolder, MappingElement, id="dict-explicit-levenshtein"), | ||
| ], | ||
| ) | ||
| def test_dict_in_sub_field_warns_instead_of_raising( | ||
| holder, element, include_confusion_matrix | ||
| ): | ||
| gt = holder(items=[element(key="k", value={"text": "p"})]) | ||
| pred = holder(items=[element(key="k", value={"text": "q"})]) | ||
|
|
||
| with pytest.warns(UserWarning, match="holds a mapping"): | ||
| result = gt.compare_with( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.[], and[]vs[](see line 553).Any/Unionchanges: FD to TP and TP to FD, including wrong-class pairs.The PR description says
Noneand"""count as before", which is false against[].There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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],Dictandstr, and also spellings such asSequence[str],Sequence[Inner]andOptional[Annotated[Inner, Field(...)]]. Earlier versions tried to list every input that moves, and kept missing some, such as aDecimalorUUIDagainst its string, twoEnumclasses,Inneragainst[Inner], orfrozenset()againstNone. Their "count as before" sentence was also false for theSequenceandAnnotatedspellings, which now count as at top level. The bullets are now examples:TypeError, and now warns and counts an FD;DecimalorUUIDagainst its string, twoEnumclasses,Inner(a="x")against[Inner(a="x")];(),frozenset(),b" "or" ", is no longer a TN against a null one;AnyorSequence[...]alike;Inner(a="hotel")vsInner(a="hotels")at 0.9 is an FD inAnyorOptional[Annotated[Inner, Field(...)]], as it already was inOptional[Inner];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
SequenceandAnnotatedrows, each against top level. The entry still names theAttributeErrorcrash 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 owncompare_with()also returns a fixed score, such asLeaf(d=[Inner(a="x")])againstLeaf(d=[Point(x=1)]), one TP from thatcompare_with(), 823c451; a list-annotated sub-field such asList[Any]falls back the same way when the list's first element's class doesn't declare it as a list, efa47ca), the plain pydanticTypeError, 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 withNoneacross pairs keeps one shape underaggregate: one read by value keeps every pair as one leaf, and one that goes to the dispatcher directly, such asOptional[Inner], keeps the models' fields and leaves theNonepair 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,PetvsCatandInner(a="x")vsOther(c="z")at the default threshold), and an empty list read as null. The "Nested lists" note inclassification-logic.mdnow 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 afilterwarnings = errorrun raises there, where dev was silent (a5e8aa0, 9ab8ec9, pinned in f1aa451 and dfc5cc1).overall_scoreis 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, everyoverallcount 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()orb""against[]is an FN (the reverse an FA), where top level gives an FD.aggregatefollows 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 scoringStructuredModelstill 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 aboutNoneand""against[], and its[]vs[]row and overlap section were stale.